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/
6 // Redistribution and use in source and binary forms, with or without
7 // modification, are permitted provided that the following conditions are
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
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.
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.
34 using System
.Collections
.Generic
;
36 using System
.Text
.RegularExpressions
;
38 namespace Google
.Protobuf
.Reflection
41 /// Contains lookup tables containing all the descriptors defined in a particular file.
43 internal sealed class DescriptorPool
45 private readonly IDictionary
<string, IDescriptor
> descriptorsByName
=
46 new Dictionary
<string, IDescriptor
>();
48 private readonly IDictionary
<DescriptorIntPair
, FieldDescriptor
> fieldsByNumber
=
49 new Dictionary
<DescriptorIntPair
, FieldDescriptor
>();
51 private readonly IDictionary
<DescriptorIntPair
, EnumValueDescriptor
> enumValuesByNumber
=
52 new Dictionary
<DescriptorIntPair
, EnumValueDescriptor
>();
54 private readonly HashSet
<FileDescriptor
> dependencies
;
56 internal DescriptorPool(FileDescriptor
[] dependencyFiles
)
58 dependencies
= new HashSet
<FileDescriptor
>();
59 for (int i
= 0; i
< dependencyFiles
.Length
; i
++)
61 dependencies
.Add(dependencyFiles
[i
]);
62 ImportPublicDependencies(dependencyFiles
[i
]);
65 foreach (FileDescriptor dependency
in dependencyFiles
)
67 AddPackage(dependency
.Package
, dependency
);
71 private void ImportPublicDependencies(FileDescriptor file
)
73 foreach (FileDescriptor dependency
in file
.PublicDependencies
)
75 if (dependencies
.Add(dependency
))
77 ImportPublicDependencies(dependency
);
83 /// Finds a symbol of the given name within the pool.
85 /// <typeparam name="T">The type of symbol to look for</typeparam>
86 /// <param name="fullName">Fully-qualified name to look up</param>
87 /// <returns>The symbol with the given name and type,
88 /// or null if the symbol doesn't exist or has the wrong type</returns>
89 internal T FindSymbol
<T
>(string fullName
) where T
: class
92 descriptorsByName
.TryGetValue(fullName
, out result
);
93 T descriptor
= result
as T
;
94 if (descriptor
!= null)
99 foreach (FileDescriptor dependency
in dependencies
)
101 dependency
.DescriptorPool
.descriptorsByName
.TryGetValue(fullName
, out result
);
102 descriptor
= result
as T
;
103 if (descriptor
!= null)
113 /// Adds a package to the symbol tables. If a package by the same name
114 /// already exists, that is fine, but if some other kind of symbol
115 /// exists under the same name, an exception is thrown. If the package
116 /// has multiple components, this also adds the parent package(s).
118 internal void AddPackage(string fullName
, FileDescriptor file
)
120 int dotpos
= fullName
.LastIndexOf('.');
124 AddPackage(fullName
.Substring(0, dotpos
), file
);
125 name
= fullName
.Substring(dotpos
+ 1);
133 if (descriptorsByName
.TryGetValue(fullName
, out old
))
135 if (!(old
is PackageDescriptor
))
137 throw new DescriptorValidationException(file
,
139 "\" is already defined (as something other than a " +
140 "package) in file \"" + old
.File
.Name
+ "\".");
143 descriptorsByName
[fullName
] = new PackageDescriptor(name
, fullName
, file
);
147 /// Adds a symbol to the symbol table.
149 /// <exception cref="DescriptorValidationException">The symbol already existed
150 /// in the symbol table.</exception>
151 internal void AddSymbol(IDescriptor descriptor
)
153 ValidateSymbolName(descriptor
);
154 String fullName
= descriptor
.FullName
;
157 if (descriptorsByName
.TryGetValue(fullName
, out old
))
159 int dotPos
= fullName
.LastIndexOf('.');
161 if (descriptor
.File
== old
.File
)
165 message
= "\"" + fullName
+ "\" is already defined.";
169 message
= "\"" + fullName
.Substring(dotPos
+ 1) + "\" is already defined in \"" +
170 fullName
.Substring(0, dotPos
) + "\".";
175 message
= "\"" + fullName
+ "\" is already defined in file \"" + old
.File
.Name
+ "\".";
177 throw new DescriptorValidationException(descriptor
, message
);
179 descriptorsByName
[fullName
] = descriptor
;
182 private static readonly Regex ValidationRegex
= new Regex("^[_A-Za-z][_A-Za-z0-9]*$",
183 FrameworkPortability
.CompiledRegexWhereAvailable
);
186 /// Verifies that the descriptor's name is valid (i.e. it contains
187 /// only letters, digits and underscores, and does not start with a digit).
189 /// <param name="descriptor"></param>
190 private static void ValidateSymbolName(IDescriptor descriptor
)
192 if (descriptor
.Name
== "")
194 throw new DescriptorValidationException(descriptor
, "Missing name.");
196 if (!ValidationRegex
.IsMatch(descriptor
.Name
))
198 throw new DescriptorValidationException(descriptor
,
199 "\"" + descriptor
.Name
+ "\" is not a valid identifier.");
204 /// Returns the field with the given number in the given descriptor,
205 /// or null if it can't be found.
207 internal FieldDescriptor
FindFieldByNumber(MessageDescriptor messageDescriptor
, int number
)
210 fieldsByNumber
.TryGetValue(new DescriptorIntPair(messageDescriptor
, number
), out ret
);
214 internal EnumValueDescriptor
FindEnumValueByNumber(EnumDescriptor enumDescriptor
, int number
)
216 EnumValueDescriptor ret
;
217 enumValuesByNumber
.TryGetValue(new DescriptorIntPair(enumDescriptor
, number
), out ret
);
222 /// Adds a field to the fieldsByNumber table.
224 /// <exception cref="DescriptorValidationException">A field with the same
225 /// containing type and number already exists.</exception>
226 internal void AddFieldByNumber(FieldDescriptor field
)
228 DescriptorIntPair key
= new DescriptorIntPair(field
.ContainingType
, field
.FieldNumber
);
230 if (fieldsByNumber
.TryGetValue(key
, out old
))
232 throw new DescriptorValidationException(field
, "Field number " + field
.FieldNumber
+
233 "has already been used in \"" +
234 field
.ContainingType
.FullName
+
235 "\" by field \"" + old
.Name
+ "\".");
237 fieldsByNumber
[key
] = field
;
241 /// Adds an enum value to the enumValuesByNumber table. If an enum value
242 /// with the same type and number already exists, this method does nothing.
243 /// (This is allowed; the first value defined with the number takes precedence.)
245 internal void AddEnumValueByNumber(EnumValueDescriptor enumValue
)
247 DescriptorIntPair key
= new DescriptorIntPair(enumValue
.EnumDescriptor
, enumValue
.Number
);
248 if (!enumValuesByNumber
.ContainsKey(key
))
250 enumValuesByNumber
[key
] = enumValue
;
255 /// Looks up a descriptor by name, relative to some other descriptor.
256 /// The name may be fully-qualified (with a leading '.'), partially-qualified,
257 /// or unqualified. C++-like name lookup semantics are used to search for the
258 /// matching descriptor.
261 /// This isn't heavily optimized, but it's only used during cross linking anyway.
262 /// If it starts being used more widely, we should look at performance more carefully.
264 internal IDescriptor
LookupSymbol(string name
, IDescriptor relativeTo
)
267 if (name
.StartsWith("."))
269 // Fully-qualified name.
270 result
= FindSymbol
<IDescriptor
>(name
.Substring(1));
274 // If "name" is a compound identifier, we want to search for the
275 // first component of it, then search within it for the rest.
276 int firstPartLength
= name
.IndexOf('.');
277 string firstPart
= firstPartLength
== -1 ? name
: name
.Substring(0, firstPartLength
);
279 // We will search each parent scope of "relativeTo" looking for the
281 StringBuilder scopeToTry
= new StringBuilder(relativeTo
.FullName
);
285 // Chop off the last component of the scope.
287 int dotpos
= scopeToTry
.ToString().LastIndexOf(".");
290 result
= FindSymbol
<IDescriptor
>(name
);
295 scopeToTry
.Length
= dotpos
+ 1;
297 // Append firstPart and try to find.
298 scopeToTry
.Append(firstPart
);
299 result
= FindSymbol
<IDescriptor
>(scopeToTry
.ToString());
303 if (firstPartLength
!= -1)
305 // We only found the first part of the symbol. Now look for
306 // the whole thing. If this fails, we *don't* want to keep
307 // searching parent scopes.
308 scopeToTry
.Length
= dotpos
+ 1;
309 scopeToTry
.Append(name
);
310 result
= FindSymbol
<IDescriptor
>(scopeToTry
.ToString());
315 // Not found. Remove the name so we can try again.
316 scopeToTry
.Length
= dotpos
;
323 throw new DescriptorValidationException(relativeTo
, "\"" + name
+ "\" is not defined.");
332 /// Struct used to hold the keys for the fieldByNumber table.
334 private struct DescriptorIntPair
: IEquatable
<DescriptorIntPair
>
336 private readonly int number
;
337 private readonly IDescriptor descriptor
;
339 internal DescriptorIntPair(IDescriptor descriptor
, int number
)
341 this.number
= number
;
342 this.descriptor
= descriptor
;
345 public bool Equals(DescriptorIntPair other
)
347 return descriptor
== other
.descriptor
348 && number
== other
.number
;
351 public override bool Equals(object obj
)
353 if (obj
is DescriptorIntPair
)
355 return Equals((DescriptorIntPair
) obj
);
360 public override int GetHashCode()
362 return descriptor
.GetHashCode()*((1 << 16) - 1) + number
;