1 #region Copyright notice and license 2 // Protocol Buffers - Google's data interchange format 3 // Copyright 2015 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.Linq; 37 using Google.Protobuf.Collections; 38 using Google.Protobuf.Compatibility; 39 40 namespace Google.Protobuf.Reflection 41 { 42 /// <summary> 43 /// Describes a "oneof" field collection in a message type: a set of 44 /// fields of which at most one can be set in any particular message. 45 /// </summary> 46 public sealed class OneofDescriptor : DescriptorBase 47 { 48 private MessageDescriptor containingType; 49 private IList<FieldDescriptor> fields; 50 private readonly OneofAccessor accessor; 51 OneofDescriptor(OneofDescriptorProto proto, FileDescriptor file, MessageDescriptor parent, int index, string clrName)52 internal OneofDescriptor(OneofDescriptorProto proto, FileDescriptor file, MessageDescriptor parent, int index, string clrName) 53 : base(file, file.ComputeFullName(parent, proto.Name), index) 54 { 55 this.Proto = proto; 56 containingType = parent; 57 file.DescriptorPool.AddSymbol(this); 58 59 // It's useful to determine whether or not this is a synthetic oneof before cross-linking. That means 60 // diving into the proto directly rather than using FieldDescriptor, but that's okay. 61 var firstFieldInOneof = parent.Proto.Field.FirstOrDefault(fieldProto => fieldProto.HasOneofIndex && fieldProto.OneofIndex == index); 62 IsSynthetic = firstFieldInOneof?.Proto3Optional ?? false; 63 64 accessor = CreateAccessor(clrName); 65 } 66 67 /// <summary> 68 /// The brief name of the descriptor's target. 69 /// </summary> 70 public override string Name => Proto.Name; 71 72 // Visible for testing 73 internal OneofDescriptorProto Proto { get; } 74 75 /// <summary> 76 /// Returns a clone of the underlying <see cref="OneofDescriptorProto"/> describing this oneof. 77 /// Note that a copy is taken every time this method is called, so clients using it frequently 78 /// (and not modifying it) may want to cache the returned value. 79 /// </summary> 80 /// <returns>A protobuf representation of this oneof descriptor.</returns> ToProto()81 public OneofDescriptorProto ToProto() => Proto.Clone(); 82 83 /// <summary> 84 /// Gets the message type containing this oneof. 85 /// </summary> 86 /// <value> 87 /// The message type containing this oneof. 88 /// </value> 89 public MessageDescriptor ContainingType 90 { 91 get { return containingType; } 92 } 93 94 /// <summary> 95 /// Gets the fields within this oneof, in declaration order. 96 /// </summary> 97 /// <value> 98 /// The fields within this oneof, in declaration order. 99 /// </value> 100 public IList<FieldDescriptor> Fields { get { return fields; } } 101 102 /// <summary> 103 /// Returns <c>true</c> if this oneof is a synthetic oneof containing a proto3 optional field; 104 /// <c>false</c> otherwise. 105 /// </summary> 106 public bool IsSynthetic { get; } 107 108 /// <summary> 109 /// Gets an accessor for reflective access to the values associated with the oneof 110 /// in a particular message. 111 /// </summary> 112 /// <remarks> 113 /// <para> 114 /// In descriptors for generated code, the value returned by this property will always be non-null. 115 /// </para> 116 /// <para> 117 /// In dynamically loaded descriptors, the value returned by this property will current be null; 118 /// if and when dynamic messages are supported, it will return a suitable accessor to work with 119 /// them. 120 /// </para> 121 /// </remarks> 122 /// <value> 123 /// The accessor used for reflective access. 124 /// </value> 125 public OneofAccessor Accessor { get { return accessor; } } 126 127 /// <summary> 128 /// The (possibly empty) set of custom options for this oneof. 129 /// </summary> 130 [Obsolete("CustomOptions are obsolete. Use the GetOptions method.")] 131 public CustomOptions CustomOptions => new CustomOptions(Proto.Options?._extensions?.ValuesByNumber); 132 133 /// <summary> 134 /// The <c>OneofOptions</c>, defined in <c>descriptor.proto</c>. 135 /// If the options message is not present (i.e. there are no options), <c>null</c> is returned. 136 /// Custom options can be retrieved as extensions of the returned message. 137 /// NOTE: A defensive copy is created each time this property is retrieved. 138 /// </summary> GetOptions()139 public OneofOptions GetOptions() => Proto.Options?.Clone(); 140 141 /// <summary> 142 /// Gets a single value oneof option for this descriptor 143 /// </summary> 144 [Obsolete("GetOption is obsolete. Use the GetOptions() method.")] GetOption(Extension<OneofOptions, T> extension)145 public T GetOption<T>(Extension<OneofOptions, T> extension) 146 { 147 var value = Proto.Options.GetExtension(extension); 148 return value is IDeepCloneable<T> ? (value as IDeepCloneable<T>).Clone() : value; 149 } 150 151 /// <summary> 152 /// Gets a repeated value oneof option for this descriptor 153 /// </summary> 154 [Obsolete("GetOption is obsolete. Use the GetOptions() method.")] GetOption(RepeatedExtension<OneofOptions, T> extension)155 public RepeatedField<T> GetOption<T>(RepeatedExtension<OneofOptions, T> extension) 156 { 157 return Proto.Options.GetExtension(extension).Clone(); 158 } 159 CrossLink()160 internal void CrossLink() 161 { 162 List<FieldDescriptor> fieldCollection = new List<FieldDescriptor>(); 163 foreach (var field in ContainingType.Fields.InDeclarationOrder()) 164 { 165 if (field.ContainingOneof == this) 166 { 167 fieldCollection.Add(field); 168 } 169 } 170 fields = new ReadOnlyCollection<FieldDescriptor>(fieldCollection); 171 } 172 CreateAccessor(string clrName)173 private OneofAccessor CreateAccessor(string clrName) 174 { 175 // We won't have a CLR name if this is from a dynamically-loaded FileDescriptor. 176 // TODO: Support dynamic messages. 177 if (clrName == null) 178 { 179 return null; 180 } 181 if (IsSynthetic) 182 { 183 return OneofAccessor.ForSyntheticOneof(this); 184 } 185 else 186 { 187 var caseProperty = containingType.ClrType.GetProperty(clrName + "Case"); 188 if (caseProperty == null) 189 { 190 throw new DescriptorValidationException(this, $"Property {clrName}Case not found in {containingType.ClrType}"); 191 } 192 if (!caseProperty.CanRead) 193 { 194 throw new ArgumentException($"Cannot read from property {clrName}Case in {containingType.ClrType}"); 195 } 196 var clearMethod = containingType.ClrType.GetMethod("Clear" + clrName); 197 if (clearMethod == null) 198 { 199 throw new DescriptorValidationException(this, $"Method Clear{clrName} not found in {containingType.ClrType}"); 200 } 201 return OneofAccessor.ForRegularOneof(this, caseProperty, clearMethod); 202 } 203 } 204 } 205 } 206