1 #region Copyright notice and license 2 // Protocol Buffers - Google's data interchange format 3 // Copyright 2008 Google Inc. All rights reserved. 4 // https://developers.google.com/protocol-buffers/ 5 // 6 // Redistribution and use in source and binary forms, with or without 7 // modification, are permitted provided that the following conditions are 8 // met: 9 // 10 // * Redistributions of source code must retain the above copyright 11 // notice, this list of conditions and the following disclaimer. 12 // * Redistributions in binary form must reproduce the above 13 // copyright notice, this list of conditions and the following disclaimer 14 // in the documentation and/or other materials provided with the 15 // distribution. 16 // * Neither the name of Google Inc. nor the names of its 17 // contributors may be used to endorse or promote products derived from 18 // this software without specific prior written permission. 19 // 20 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 21 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 23 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 24 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 25 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 26 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 27 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 28 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 29 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 30 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 #endregion 32 33 using System; 34 using System.Collections.Generic; 35 using System.Collections.ObjectModel; 36 using System.Diagnostics.CodeAnalysis; 37 using System.Linq; 38 using System.Reflection; 39 #if NET35 40 // Needed for ReadOnlyDictionary, which does not exist in .NET 3.5 41 using Google.Protobuf.Collections; 42 #endif 43 44 namespace Google.Protobuf.Reflection 45 { 46 /// <summary> 47 /// Describes a message type. 48 /// </summary> 49 public sealed class MessageDescriptor : DescriptorBase 50 { 51 private static readonly HashSet<string> WellKnownTypeNames = new HashSet<string> 52 { 53 "google/protobuf/any.proto", 54 "google/protobuf/api.proto", 55 "google/protobuf/duration.proto", 56 "google/protobuf/empty.proto", 57 "google/protobuf/wrappers.proto", 58 "google/protobuf/timestamp.proto", 59 "google/protobuf/field_mask.proto", 60 "google/protobuf/source_context.proto", 61 "google/protobuf/struct.proto", 62 "google/protobuf/type.proto", 63 }; 64 65 private readonly IList<FieldDescriptor> fieldsInDeclarationOrder; 66 private readonly IList<FieldDescriptor> fieldsInNumberOrder; 67 private readonly IDictionary<string, FieldDescriptor> jsonFieldMap; 68 private Func<IMessage, bool> extensionSetIsInitialized; 69 MessageDescriptor(DescriptorProto proto, FileDescriptor file, MessageDescriptor parent, int typeIndex, GeneratedClrTypeInfo generatedCodeInfo)70 internal MessageDescriptor(DescriptorProto proto, FileDescriptor file, MessageDescriptor parent, int typeIndex, GeneratedClrTypeInfo generatedCodeInfo) 71 : base(file, file.ComputeFullName(parent, proto.Name), typeIndex) 72 { 73 Proto = proto; 74 Parser = generatedCodeInfo?.Parser; 75 ClrType = generatedCodeInfo?.ClrType; 76 ContainingType = parent; 77 78 // If generatedCodeInfo is null, we just won't generate an accessor for any fields. 79 Oneofs = DescriptorUtil.ConvertAndMakeReadOnly( 80 proto.OneofDecl, 81 (oneof, index) => 82 new OneofDescriptor(oneof, file, this, index, generatedCodeInfo?.OneofNames[index])); 83 84 int syntheticOneofCount = 0; 85 foreach (var oneof in Oneofs) 86 { 87 if (oneof.IsSynthetic) 88 { 89 syntheticOneofCount++; 90 } 91 else if (syntheticOneofCount != 0) 92 { 93 throw new ArgumentException("All synthetic oneofs should come after real oneofs"); 94 } 95 } 96 RealOneofCount = Oneofs.Count - syntheticOneofCount; 97 98 NestedTypes = DescriptorUtil.ConvertAndMakeReadOnly( 99 proto.NestedType, 100 (type, index) => 101 new MessageDescriptor(type, file, this, index, generatedCodeInfo?.NestedTypes[index])); 102 103 EnumTypes = DescriptorUtil.ConvertAndMakeReadOnly( 104 proto.EnumType, 105 (type, index) => 106 new EnumDescriptor(type, file, this, index, generatedCodeInfo?.NestedEnums[index])); 107 108 Extensions = new ExtensionCollection(this, generatedCodeInfo?.Extensions); 109 110 fieldsInDeclarationOrder = DescriptorUtil.ConvertAndMakeReadOnly( 111 proto.Field, 112 (field, index) => 113 new FieldDescriptor(field, file, this, index, generatedCodeInfo?.PropertyNames[index], null)); 114 fieldsInNumberOrder = new ReadOnlyCollection<FieldDescriptor>(fieldsInDeclarationOrder.OrderBy(field => field.FieldNumber).ToArray()); 115 // TODO: Use field => field.Proto.JsonName when we're confident it's appropriate. (And then use it in the formatter, too.) 116 jsonFieldMap = CreateJsonFieldMap(fieldsInNumberOrder); 117 file.DescriptorPool.AddSymbol(this); 118 Fields = new FieldCollection(this); 119 } 120 CreateJsonFieldMap(IList<FieldDescriptor> fields)121 private static ReadOnlyDictionary<string, FieldDescriptor> CreateJsonFieldMap(IList<FieldDescriptor> fields) 122 { 123 var map = new Dictionary<string, FieldDescriptor>(); 124 foreach (var field in fields) 125 { 126 map[field.Name] = field; 127 map[field.JsonName] = field; 128 } 129 return new ReadOnlyDictionary<string, FieldDescriptor>(map); 130 } 131 132 /// <summary> 133 /// The brief name of the descriptor's target. 134 /// </summary> 135 public override string Name => Proto.Name; 136 GetNestedDescriptorListForField(int fieldNumber)137 internal override IReadOnlyList<DescriptorBase> GetNestedDescriptorListForField(int fieldNumber) 138 { 139 switch (fieldNumber) 140 { 141 case DescriptorProto.FieldFieldNumber: 142 return (IReadOnlyList<DescriptorBase>) fieldsInDeclarationOrder; 143 case DescriptorProto.NestedTypeFieldNumber: 144 return (IReadOnlyList<DescriptorBase>) NestedTypes; 145 case DescriptorProto.EnumTypeFieldNumber: 146 return (IReadOnlyList<DescriptorBase>) EnumTypes; 147 default: 148 return null; 149 } 150 } 151 152 internal DescriptorProto Proto { get; } 153 154 /// <summary> 155 /// Returns a clone of the underlying <see cref="DescriptorProto"/> describing this message. 156 /// Note that a copy is taken every time this method is called, so clients using it frequently 157 /// (and not modifying it) may want to cache the returned value. 158 /// </summary> 159 /// <returns>A protobuf representation of this message descriptor.</returns> ToProto()160 public DescriptorProto ToProto() => Proto.Clone(); 161 IsExtensionsInitialized(IMessage message)162 internal bool IsExtensionsInitialized(IMessage message) 163 { 164 if (Proto.ExtensionRange.Count == 0) 165 { 166 return true; 167 } 168 169 if (extensionSetIsInitialized == null) 170 { 171 extensionSetIsInitialized = ReflectionUtil.CreateIsInitializedCaller(ClrType); 172 } 173 174 return extensionSetIsInitialized(message); 175 } 176 177 /// <summary> 178 /// The CLR type used to represent message instances from this descriptor. 179 /// </summary> 180 /// <remarks> 181 /// <para> 182 /// The value returned by this property will be non-null for all regular fields. However, 183 /// if a message containing a map field is introspected, the list of nested messages will include 184 /// an auto-generated nested key/value pair message for the field. This is not represented in any 185 /// generated type, so this property will return null in such cases. 186 /// </para> 187 /// <para> 188 /// For wrapper types (<see cref="Google.Protobuf.WellKnownTypes.StringValue"/> and the like), the type returned here 189 /// will be the generated message type, not the native type used by reflection for fields of those types. Code 190 /// using reflection should call <see cref="IsWrapperType"/> to determine whether a message descriptor represents 191 /// a wrapper type, and handle the result appropriately. 192 /// </para> 193 /// </remarks> 194 [DynamicallyAccessedMembers(GeneratedClrTypeInfo.MessageAccessibility)] 195 public Type ClrType { get; } 196 197 /// <summary> 198 /// A parser for this message type. 199 /// </summary> 200 /// <remarks> 201 /// <para> 202 /// As <see cref="MessageDescriptor"/> is not generic, this cannot be statically 203 /// typed to the relevant type, but it should produce objects of a type compatible with <see cref="ClrType"/>. 204 /// </para> 205 /// <para> 206 /// The value returned by this property will be non-null for all regular fields. However, 207 /// if a message containing a map field is introspected, the list of nested messages will include 208 /// an auto-generated nested key/value pair message for the field. No message parser object is created for 209 /// such messages, so this property will return null in such cases. 210 /// </para> 211 /// <para> 212 /// For wrapper types (<see cref="Google.Protobuf.WellKnownTypes.StringValue"/> and the like), the parser returned here 213 /// will be the generated message type, not the native type used by reflection for fields of those types. Code 214 /// using reflection should call <see cref="IsWrapperType"/> to determine whether a message descriptor represents 215 /// a wrapper type, and handle the result appropriately. 216 /// </para> 217 /// </remarks> 218 public MessageParser Parser { get; } 219 220 /// <summary> 221 /// Returns whether this message is one of the "well known types" which may have runtime/protoc support. 222 /// </summary> 223 internal bool IsWellKnownType => File.Package == "google.protobuf" && WellKnownTypeNames.Contains(File.Name); 224 225 /// <summary> 226 /// Returns whether this message is one of the "wrapper types" used for fields which represent primitive values 227 /// with the addition of presence. 228 /// </summary> 229 internal bool IsWrapperType => File.Package == "google.protobuf" && File.Name == "google/protobuf/wrappers.proto"; 230 231 /// <value> 232 /// If this is a nested type, get the outer descriptor, otherwise null. 233 /// </value> 234 public MessageDescriptor ContainingType { get; } 235 236 /// <value> 237 /// A collection of fields, which can be retrieved by name or field number. 238 /// </value> 239 public FieldCollection Fields { get; } 240 241 /// <summary> 242 /// An unmodifiable list of extensions defined in this message's scope. 243 /// Note that some extensions may be incomplete (FieldDescriptor.Extension may be null) 244 /// if they are declared in a file generated using a version of protoc that did not fully 245 /// support extensions in C#. 246 /// </summary> 247 public ExtensionCollection Extensions { get; } 248 249 /// <value> 250 /// An unmodifiable list of this message type's nested types. 251 /// </value> 252 public IList<MessageDescriptor> NestedTypes { get; } 253 254 /// <value> 255 /// An unmodifiable list of this message type's enum types. 256 /// </value> 257 public IList<EnumDescriptor> EnumTypes { get; } 258 259 /// <value> 260 /// An unmodifiable list of the "oneof" field collections in this message type. 261 /// All "real" oneofs (where <see cref="OneofDescriptor.IsSynthetic"/> returns false) 262 /// come before synthetic ones. 263 /// </value> 264 public IList<OneofDescriptor> Oneofs { get; } 265 266 /// <summary> 267 /// The number of real "oneof" descriptors in this message type. Every element in <see cref="Oneofs"/> 268 /// with an index less than this will have a <see cref="OneofDescriptor.IsSynthetic"/> property value 269 /// of <c>false</c>; every element with an index greater than or equal to this will have a 270 /// <see cref="OneofDescriptor.IsSynthetic"/> property value of <c>true</c>. 271 /// </summary> 272 public int RealOneofCount { get; } 273 274 /// <summary> 275 /// Finds a field by field name. 276 /// </summary> 277 /// <param name="name">The unqualified name of the field (e.g. "foo").</param> 278 /// <returns>The field's descriptor, or null if not found.</returns> 279 public FieldDescriptor FindFieldByName(String name) => File.DescriptorPool.FindSymbol<FieldDescriptor>(FullName + "." + name); 280 281 /// <summary> 282 /// Finds a field by field number. 283 /// </summary> 284 /// <param name="number">The field number within this message type.</param> 285 /// <returns>The field's descriptor, or null if not found.</returns> FindFieldByNumber(int number)286 public FieldDescriptor FindFieldByNumber(int number) => File.DescriptorPool.FindFieldByNumber(this, number); 287 288 /// <summary> 289 /// Finds a nested descriptor by name. The is valid for fields, nested 290 /// message types, oneofs and enums. 291 /// </summary> 292 /// <param name="name">The unqualified name of the descriptor, e.g. "Foo"</param> 293 /// <returns>The descriptor, or null if not found.</returns> 294 public T FindDescriptor<T>(string name) where T : class, IDescriptor => 295 File.DescriptorPool.FindSymbol<T>(FullName + "." + name); 296 297 /// <summary> 298 /// The (possibly empty) set of custom options for this message. 299 /// </summary> 300 [Obsolete("CustomOptions are obsolete. Use the GetOptions() method.")] 301 public CustomOptions CustomOptions => new CustomOptions(Proto.Options?._extensions?.ValuesByNumber); 302 303 /// <summary> 304 /// The <c>MessageOptions</c>, defined in <c>descriptor.proto</c>. 305 /// If the options message is not present (i.e. there are no options), <c>null</c> is returned. 306 /// Custom options can be retrieved as extensions of the returned message. 307 /// NOTE: A defensive copy is created each time this property is retrieved. 308 /// </summary> GetOptions()309 public MessageOptions GetOptions() => Proto.Options?.Clone(); 310 311 /// <summary> 312 /// Gets a single value message option for this descriptor 313 /// </summary> 314 [Obsolete("GetOption is obsolete. Use the GetOptions() method.")] GetOption(Extension<MessageOptions, T> extension)315 public T GetOption<T>(Extension<MessageOptions, T> extension) 316 { 317 var value = Proto.Options.GetExtension(extension); 318 return value is IDeepCloneable<T> ? (value as IDeepCloneable<T>).Clone() : value; 319 } 320 321 /// <summary> 322 /// Gets a repeated value message option for this descriptor 323 /// </summary> 324 [Obsolete("GetOption is obsolete. Use the GetOptions() method.")] GetOption(RepeatedExtension<MessageOptions, T> extension)325 public Collections.RepeatedField<T> GetOption<T>(RepeatedExtension<MessageOptions, T> extension) 326 { 327 return Proto.Options.GetExtension(extension).Clone(); 328 } 329 330 /// <summary> 331 /// Looks up and cross-links all fields and nested types. 332 /// </summary> CrossLink()333 internal void CrossLink() 334 { 335 foreach (MessageDescriptor message in NestedTypes) 336 { 337 message.CrossLink(); 338 } 339 340 foreach (FieldDescriptor field in fieldsInDeclarationOrder) 341 { 342 field.CrossLink(); 343 } 344 345 foreach (OneofDescriptor oneof in Oneofs) 346 { 347 oneof.CrossLink(); 348 } 349 350 Extensions.CrossLink(); 351 } 352 353 /// <summary> 354 /// A collection to simplify retrieving the field accessor for a particular field. 355 /// </summary> 356 public sealed class FieldCollection 357 { 358 private readonly MessageDescriptor messageDescriptor; 359 FieldCollection(MessageDescriptor messageDescriptor)360 internal FieldCollection(MessageDescriptor messageDescriptor) 361 { 362 this.messageDescriptor = messageDescriptor; 363 } 364 365 /// <value> 366 /// Returns the fields in the message as an immutable list, in the order in which they 367 /// are declared in the source .proto file. 368 /// </value> InDeclarationOrder()369 public IList<FieldDescriptor> InDeclarationOrder() => messageDescriptor.fieldsInDeclarationOrder; 370 371 /// <value> 372 /// Returns the fields in the message as an immutable list, in ascending field number 373 /// order. Field numbers need not be contiguous, so there is no direct mapping from the 374 /// index in the list to the field number; to retrieve a field by field number, it is better 375 /// to use the <see cref="FieldCollection"/> indexer. 376 /// </value> InFieldNumberOrder()377 public IList<FieldDescriptor> InFieldNumberOrder() => messageDescriptor.fieldsInNumberOrder; 378 379 // TODO: consider making this public in the future. (Being conservative for now...) 380 381 /// <value> 382 /// Returns a read-only dictionary mapping the field names in this message as they're available 383 /// in the JSON representation to the field descriptors. For example, a field <c>foo_bar</c> 384 /// in the message would result two entries, one with a key <c>fooBar</c> and one with a key 385 /// <c>foo_bar</c>, both referring to the same field. 386 /// </value> ByJsonName()387 internal IDictionary<string, FieldDescriptor> ByJsonName() => messageDescriptor.jsonFieldMap; 388 389 /// <summary> 390 /// Retrieves the descriptor for the field with the given number. 391 /// </summary> 392 /// <param name="number">Number of the field to retrieve the descriptor for</param> 393 /// <returns>The accessor for the given field</returns> 394 /// <exception cref="KeyNotFoundException">The message descriptor does not contain a field 395 /// with the given number</exception> 396 public FieldDescriptor this[int number] 397 { 398 get 399 { 400 var fieldDescriptor = messageDescriptor.FindFieldByNumber(number); 401 if (fieldDescriptor == null) 402 { 403 throw new KeyNotFoundException("No such field number"); 404 } 405 return fieldDescriptor; 406 } 407 } 408 409 /// <summary> 410 /// Retrieves the descriptor for the field with the given name. 411 /// </summary> 412 /// <param name="name">Name of the field to retrieve the descriptor for</param> 413 /// <returns>The descriptor for the given field</returns> 414 /// <exception cref="KeyNotFoundException">The message descriptor does not contain a field 415 /// with the given name</exception> 416 public FieldDescriptor this[string name] 417 { 418 get 419 { 420 var fieldDescriptor = messageDescriptor.FindFieldByName(name); 421 if (fieldDescriptor == null) 422 { 423 throw new KeyNotFoundException("No such field name"); 424 } 425 return fieldDescriptor; 426 } 427 } 428 } 429 } 430 } 431