-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
TypeNameDiscriminator.cs
207 lines (192 loc) · 7.44 KB
/
TypeNameDiscriminator.cs
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
/* Copyright 2010-present MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
namespace MongoDB.Bson.Serialization
{
/// <summary>
/// Supports using type names as discriminators.
/// </summary>
public static class TypeNameDiscriminator
{
// private static fields
private static readonly HashSet<Assembly> __wellKnownAssemblies = new HashSet<Assembly>();
// static constructor
static TypeNameDiscriminator()
{
var representativeTypes = new Type[]
{
// the actual locations of these types varies depending on the target framework
typeof(object),
typeof(Queue<>),
typeof(HashSet<>),
typeof(SortedSet<>)
};
foreach (var type in representativeTypes)
{
var assembly = type.GetTypeInfo().Assembly;
__wellKnownAssemblies.Add(assembly);
}
}
// public static methods
/// <summary>
/// Resolves a type name discriminator.
/// </summary>
/// <param name="typeName">The type name.</param>
/// <returns>The type if type type name can be resolved; otherwise, null.</returns>
public static Type GetActualType(string typeName)
{
var type = Type.GetType(typeName);
if (type != null)
{
return type;
}
foreach (var assembly in __wellKnownAssemblies)
{
type = assembly.GetType(typeName);
if (type != null)
{
return type;
}
}
string genericTypeDefinitionName;
string[] typeArgumentNames;
if (TryParseGenericTypeName(typeName, out genericTypeDefinitionName, out typeArgumentNames))
{
var genericTypeDefinition = GetActualType(genericTypeDefinitionName);
if (genericTypeDefinition != null)
{
var typeArguments = new List<Type>();
foreach (var typeArgumentName in typeArgumentNames)
{
var typeArgument = GetActualType(typeArgumentName);
if (typeArgument == null)
{
break;
}
typeArguments.Add(typeArgument);
}
if (typeArguments.Count == genericTypeDefinition.GetTypeInfo().GetGenericArguments().Length)
{
return genericTypeDefinition.MakeGenericType(typeArguments.ToArray());
}
}
}
return null;
}
/// <summary>
/// Gets a type name to be used as a discriminator (like AssemblyQualifiedName but shortened for common DLLs).
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The type name.</returns>
public static string GetDiscriminator(Type type)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
var typeInfo = type.GetTypeInfo();
string typeName;
if (typeInfo.IsGenericType)
{
var typeArgumentNames = "";
foreach (var typeArgument in typeInfo.GetGenericArguments())
{
var typeArgumentName = GetDiscriminator(typeArgument);
if (typeArgumentName.IndexOf(',') != -1)
{
typeArgumentName = "[" + typeArgumentName + "]";
}
if (typeArgumentNames != "")
{
typeArgumentNames += ",";
}
typeArgumentNames += typeArgumentName;
}
typeName = type.GetGenericTypeDefinition().FullName + "[" + typeArgumentNames + "]";
}
else
{
typeName = type.FullName;
}
var assembly = typeInfo.Assembly;
string assemblyName = null;
if (!__wellKnownAssemblies.Contains(assembly))
{
assemblyName = assembly.FullName;
Match match = Regex.Match(assemblyName, "(?<dll>[^,]+), Version=[^,]+, Culture=[^,]+, PublicKeyToken=(?<token>[^,]+)");
if (match.Success)
{
var publicKeyToken = match.Groups["token"].Value;
if (publicKeyToken == "null")
{
var dllName = match.Groups["dll"].Value;
assemblyName = dllName;
}
}
}
if (assemblyName == null)
{
return typeName;
}
else
{
return typeName + ", " + assemblyName;
}
}
// private static methods
private static bool TryParseGenericTypeName(string typeName, out string genericTypeDefinitionName, out string[] typeArgumentNames)
{
var leftBracketIndex = typeName.IndexOf('[');
if (leftBracketIndex != -1)
{
genericTypeDefinitionName = typeName.Substring(0, leftBracketIndex);
var typeArgumentNamesString = typeName.Substring(leftBracketIndex + 1, typeName.Length - leftBracketIndex - 2);
var typeArgumentNamesList = new List<string>();
var startIndex = 0;
var nestingLevel = 0;
for (var index = 0; index < typeArgumentNamesString.Length; index++)
{
var c = typeArgumentNamesString[index];
switch (c)
{
case '[':
nestingLevel++;
break;
case ']':
nestingLevel--;
break;
case ',':
if (nestingLevel == 0)
{
var typeArgumentName = typeArgumentNamesString.Substring(startIndex, index - startIndex);
typeArgumentNamesList.Add(typeArgumentName);
}
break;
}
}
typeArgumentNamesList.Add(typeArgumentNamesString.Substring(startIndex));
typeArgumentNames = typeArgumentNamesList.ToArray();
return true;
}
genericTypeDefinitionName = null;
typeArgumentNames = null;
return false;
}
}
}