FileDescriptor.cs 14.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc.  All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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.
#endregion

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace Google.Protobuf.Reflection
{
    /// <summary>
    /// 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.
    /// </summary>
    public sealed class FileDescriptor : IDescriptor
    {
46
        private FileDescriptor(ByteString descriptorData, FileDescriptorProto proto, FileDescriptor[] dependencies, DescriptorPool pool, bool allowUnknownDependencies, GeneratedClrTypeInfo generatedCodeInfo)
47
        {
48 49 50 51
            SerializedData = descriptorData;
            DescriptorPool = pool;
            Proto = proto;
            Dependencies = new ReadOnlyCollection<FileDescriptor>((FileDescriptor[]) dependencies.Clone());
52

53
            PublicDependencies = DeterminePublicDependencies(this, proto, dependencies, allowUnknownDependencies);
54 55 56

            pool.AddPackage(Package, this);

57
            MessageTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.MessageType,
58
                                                                 (message, index) =>
59
                                                                 new MessageDescriptor(message, this, null, index, generatedCodeInfo.NestedTypes[index]));
60

61
            EnumTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.EnumType,
62
                                                              (enumType, index) =>
63
                                                              new EnumDescriptor(enumType, this, null, index, generatedCodeInfo.NestedEnums[index]));
64

65
            Services = DescriptorUtil.ConvertAndMakeReadOnly(proto.Service,
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
                                                             (service, index) =>
                                                             new ServiceDescriptor(service, this, index));
        }

        /// <summary>
        /// Computes the full name of a descriptor within this file, with an optional parent message.
        /// </summary>
        internal string ComputeFullName(MessageDescriptor parent, string name)
        {
            if (parent != null)
            {
                return parent.FullName + "." + name;
            }
            if (Package.Length > 0)
            {
                return Package + "." + name;
            }
            return name;
        }

        /// <summary>
        /// Extracts public dependencies from direct dependencies. This is a static method despite its
        /// first parameter, as the value we're in the middle of constructing is only used for exceptions.
        /// </summary>
        private static IList<FileDescriptor> DeterminePublicDependencies(FileDescriptor @this, FileDescriptorProto proto, FileDescriptor[] dependencies, bool allowUnknownDependencies)
        {
            var nameToFileMap = new Dictionary<string, FileDescriptor>();
            foreach (var file in dependencies)
            {
                nameToFileMap[file.Name] = file;
            }
            var publicDependencies = new List<FileDescriptor>();
            for (int i = 0; i < proto.PublicDependency.Count; i++)
            {
                int index = proto.PublicDependency[i];
                if (index < 0 || index >= proto.Dependency.Count)
                {
                    throw new DescriptorValidationException(@this, "Invalid public dependency index.");
                }
                string name = proto.Dependency[index];
                FileDescriptor file = nameToFileMap[name];
                if (file == null)
                {
                    if (!allowUnknownDependencies)
                    {
                        throw new DescriptorValidationException(@this, "Invalid public dependency: " + name);
                    }
                    // Ignore unknown dependencies.
                }
                else
                {
                    publicDependencies.Add(file);
                }
            }
            return new ReadOnlyCollection<FileDescriptor>(publicDependencies);
        }

        /// <value>
        /// The descriptor in its protocol message representation.
        /// </value>
126
        internal FileDescriptorProto Proto { get; }
127 128 129 130

        /// <value>
        /// The file name.
        /// </value>
131
        public string Name => Proto.Name;
132 133 134 135 136

        /// <summary>
        /// The package as declared in the .proto file. This may or may not
        /// be equivalent to the .NET namespace of the generated classes.
        /// </summary>
137
        public string Package => Proto.Package;
138 139 140 141

        /// <value>
        /// Unmodifiable list of top-level message types declared in this file.
        /// </value>
142
        public IList<MessageDescriptor> MessageTypes { get; }
143 144 145 146

        /// <value>
        /// Unmodifiable list of top-level enum types declared in this file.
        /// </value>
147
        public IList<EnumDescriptor> EnumTypes { get; }
148 149 150 151

        /// <value>
        /// Unmodifiable list of top-level services declared in this file.
        /// </value>
152
        public IList<ServiceDescriptor> Services { get; }
153 154 155 156

        /// <value>
        /// Unmodifiable list of this file's dependencies (imports).
        /// </value>
157
        public IList<FileDescriptor> Dependencies { get; }
158 159 160 161

        /// <value>
        /// Unmodifiable list of this file's public dependencies (public imports).
        /// </value>
162
        public IList<FileDescriptor> PublicDependencies { get; }
163

164 165 166
        /// <value>
        /// The original serialized binary form of this descriptor.
        /// </value>
167
        public ByteString SerializedData { get; }
168

169 170 171
        /// <value>
        /// Implementation of IDescriptor.FullName - just returns the same as Name.
        /// </value>
172
        string IDescriptor.FullName => Name;
173 174 175 176

        /// <value>
        /// Implementation of IDescriptor.File - just returns this descriptor.
        /// </value>
177
        FileDescriptor IDescriptor.File => this;
178 179 180 181

        /// <value>
        /// Pool containing symbol descriptors.
        /// </value>
182
        internal DescriptorPool DescriptorPool { get; }
183 184 185 186 187

        /// <summary>
        /// Finds a type (message, enum, service or extension) in the file by name. Does not find nested types.
        /// </summary>
        /// <param name="name">The unqualified type name to look for.</param>
188
        /// <typeparam name="T">The type of descriptor to look for</typeparam>
189 190 191 192 193 194 195 196 197 198 199 200 201 202
        /// <returns>The type's descriptor, or null if not found.</returns>
        public T FindTypeByName<T>(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;
            }
203
            T result = DescriptorPool.FindSymbol<T>(name);
204 205 206 207 208 209
            if (result != null && result.File == this)
            {
                return result;
            }
            return null;
        }
210

211 212 213
        /// <summary>
        /// Builds a FileDescriptor from its protocol buffer representation.
        /// </summary>
214 215 216
        /// <param name="descriptorData">The original serialized descriptor data.
        /// We have only limited proto2 support, so serializing FileDescriptorProto
        /// would not necessarily give us this.</param>
217 218 219 220 221
        /// <param name="proto">The protocol message form of the FileDescriptor.</param>
        /// <param name="dependencies">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.</param>
        /// <param name="allowUnknownDependencies">Whether unknown dependencies are ignored (true) or cause an exception to be thrown (false).</param>
222
        /// <param name="generatedCodeInfo">Details about generated code, for the purposes of reflection.</param>
223 224 225
        /// <exception cref="DescriptorValidationException">If <paramref name="proto"/> 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.</exception>
226
        private static FileDescriptor BuildFrom(ByteString descriptorData, FileDescriptorProto proto, FileDescriptor[] dependencies, bool allowUnknownDependencies, GeneratedClrTypeInfo generatedCodeInfo)
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
        {
            // 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);
243
            FileDescriptor result = new FileDescriptor(descriptorData, proto, dependencies, pool, allowUnknownDependencies, generatedCodeInfo);
244

245 246 247 248
            // Validate that the dependencies we've been passed (as FileDescriptors) are actually the ones we
            // need.
            if (dependencies.Length != proto.Dependency.Count)
            {
249 250 251 252
                throw new DescriptorValidationException(
                    result,
                    "Dependencies passed to FileDescriptor.BuildFrom() don't match " +
                    "those listed in the FileDescriptorProto.");
253
            }
254 255 256 257 258 259 260

            result.CrossLink();
            return result;
        }

        private void CrossLink()
        {
261
            foreach (MessageDescriptor message in MessageTypes)
262 263 264 265
            {
                message.CrossLink();
            }

266
            foreach (ServiceDescriptor service in Services)
267 268 269 270 271
            {
                service.CrossLink();
            }
        }

Jon Skeet's avatar
Jon Skeet committed
272
        /// <summary>
273
        /// Creates a descriptor for generated code.
Jon Skeet's avatar
Jon Skeet committed
274 275
        /// </summary>
        /// <remarks>
276 277 278
        /// This method is only designed to be used by the results of generating code with protoc,
        /// which creates the appropriate dependencies etc. It has to be public because the generated
        /// code is "external", but should not be called directly by end users.
Jon Skeet's avatar
Jon Skeet committed
279
        /// </remarks>
280 281 282
        public static FileDescriptor FromGeneratedCode(
            byte[] descriptorData,
            FileDescriptor[] dependencies,
283
            GeneratedClrTypeInfo generatedCodeInfo)
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
        {
            FileDescriptorProto proto;
            try
            {
                proto = FileDescriptorProto.Parser.ParseFrom(descriptorData);
            }
            catch (InvalidProtocolBufferException e)
            {
                throw new ArgumentException("Failed to parse protocol buffer descriptor for generated code.", e);
            }

            try
            {
                // When building descriptors for generated code, we allow unknown
                // dependencies by default.
299
                return BuildFrom(ByteString.CopyFrom(descriptorData), proto, dependencies, true, generatedCodeInfo);
300 301 302
            }
            catch (DescriptorValidationException e)
            {
303
                throw new ArgumentException($"Invalid embedded descriptor for \"{proto.Name}\".", e);
304 305
            }
        }
306 307 308 309 310 311 312

        /// <summary>
        /// Returns a <see cref="System.String" /> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String" /> that represents this instance.
        /// </returns>
313 314
        public override string ToString()
        {
315
            return $"FileDescriptor for {Name}";
316
        }
317 318 319 320 321 322 323 324 325 326 327 328 329 330

        /// <summary>
        /// Returns the file descriptor for descriptor.proto.
        /// </summary>
        /// <remarks>
        /// This is used for protos which take a direct dependency on <c>descriptor.proto</c>, typically for
        /// annotations. While <c>descriptor.proto</c> is a proto2 file, it is built into the Google.Protobuf
        /// runtime for reflection purposes. The messages are internal to the runtime as they would require
        /// proto2 semantics for full support, but the file descriptor is available via this property. The
        /// C# codegen in protoc automatically uses this property when it detects a dependency on <c>descriptor.proto</c>.
        /// </remarks>
        /// <value>
        /// The file descriptor for <c>descriptor.proto</c>.
        /// </value>
331
        public static FileDescriptor DescriptorProtoFileDescriptor { get { return DescriptorReflection.Descriptor; } }
332 333 334 335 336

        /// <summary>
        /// The (possibly empty) set of custom options for this file.
        /// </summary>
        public CustomOptions CustomOptions => Proto.Options?.CustomOptions ?? CustomOptions.Empty;
337
    }
338
}