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