-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathConfigurationBinder.Builder.cs
More file actions
397 lines (343 loc) · 19.4 KB
/
ConfigurationBinder.Builder.cs
File metadata and controls
397 lines (343 loc) · 19.4 KB
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
using Microsoft.Extensions.Configuration;
using PolyType.Abstractions;
using PolyType.Examples.Utilities;
using PolyType.Utilities;
using System.Globalization;
using System.Numerics;
namespace PolyType.Examples.ConfigurationBinder;
public static partial class ConfigurationBinderTS
{
private sealed class Builder(ITypeShapeFunc self) : TypeShapeVisitor, ITypeShapeFunc
{
private const string TypeDiscriminator = "$type";
private const string ValuesProperty = "$values";
private delegate void PropertyBinder<T>(ref T obj, IConfigurationSection section);
private static readonly Dictionary<Type, object> s_builtInParsers = GetBuiltInParsers().ToDictionary();
/// <summary>Recursively looks up or creates a binder for the specified shape.</summary>
public Func<IConfiguration, T?> GetOrAddBinder<T>(ITypeShape<T> shape) =>
(Func<IConfiguration, T?>)self.Invoke(shape)!;
object? ITypeShapeFunc.Invoke<T>(ITypeShape<T> typeShape, object? state)
{
if (s_builtInParsers.TryGetValue(typeof(T), out object? stringParser))
{
return CreateValueBinder((Func<string, T>)stringParser!);
}
return typeShape.Accept(this);
}
public override object? VisitObject<T>(IObjectTypeShape<T> objectShape, object? state = null)
{
return objectShape.Constructor is { } ctorShape
? ctorShape.Accept(this)
: CreateNotSupportedBinder<T>();
}
public override object? VisitConstructor<TDeclaringType, TArgumentState>(IConstructorShape<TDeclaringType, TArgumentState> constructorShape, object? state = null)
{
if (constructorShape.Parameters is [])
{
Func<TDeclaringType> defaultCtor = constructorShape.GetDefaultConstructor();
(string Name, PropertyBinder<TDeclaringType> Binder)[] propertyBinders = constructorShape.DeclaringType.Properties
.Where(prop => prop.HasSetter)
.Select(prop => (prop.Name, (PropertyBinder<TDeclaringType>)prop.Accept(this)!))
.ToArray();
return new Func<IConfiguration, TDeclaringType?>(configuration =>
{
if (IsNullConfiguration(configuration))
{
return default;
}
TDeclaringType obj = defaultCtor();
foreach ((string name, PropertyBinder<TDeclaringType> binder) in propertyBinders)
{
if (configuration.GetSection(name) is { } section)
{
binder(ref obj, section);
}
}
return obj;
});
}
else
{
Func<TArgumentState> argStateCtor = constructorShape.GetArgumentStateConstructor();
Constructor<TArgumentState, TDeclaringType> paramCtor = constructorShape.GetParameterizedConstructor();
(string Name, bool IsRequired, PropertyBinder<TArgumentState> Binder)[] paramBinders = constructorShape.Parameters
.Select(param => (param.Name, param.IsRequired, (PropertyBinder<TArgumentState>)param.Accept(this)!))
.ToArray();
return new Func<IConfiguration, TDeclaringType?>(configuration =>
{
if (IsNullConfiguration(configuration))
{
return default;
}
TArgumentState argState = argStateCtor();
foreach ((string name, bool isRequired, PropertyBinder<TArgumentState> binder) in paramBinders)
{
if (configuration.GetSection(name) is { } section)
{
binder(ref argState, section);
}
else if (isRequired)
{
Throw(name);
static void Throw(string name) => throw new InvalidOperationException($"Missing required configuration key '{name}'.");
}
}
return paramCtor(ref argState);
});
}
}
public override object? VisitProperty<TDeclaringType, TPropertyType>(IPropertyShape<TDeclaringType, TPropertyType> propertyShape, object? state = null)
{
Func<IConfiguration, TPropertyType?> propertyTypeBinder = GetOrAddBinder(propertyShape.PropertyType);
Setter<TDeclaringType, TPropertyType> setter = propertyShape.GetSetter();
return new PropertyBinder<TDeclaringType>((ref TDeclaringType obj, IConfigurationSection section) => setter(ref obj, propertyTypeBinder(section)!));
}
public override object? VisitParameter<TArgumentState, TParameterType>(IParameterShape<TArgumentState, TParameterType> parameterShape, object? state = null)
{
Func<IConfiguration, TParameterType?> parameterTypeBinder = GetOrAddBinder(parameterShape.ParameterType);
Setter<TArgumentState, TParameterType> setter = parameterShape.GetSetter();
return new PropertyBinder<TArgumentState>((ref TArgumentState argState, IConfigurationSection section) => setter(ref argState, parameterTypeBinder(section)!));
}
public override object? VisitEnumerable<TEnumerable, TElement>(IEnumerableTypeShape<TEnumerable, TElement> enumerableShape, object? state = null)
{
Func<IConfiguration, TElement> elementBinder = GetOrAddBinder(enumerableShape.ElementType)!;
switch (enumerableShape.ConstructionStrategy)
{
case CollectionConstructionStrategy.Mutable:
MutableCollectionConstructor<TElement, TEnumerable> defaultCtor = enumerableShape.GetDefaultConstructor();
EnumerableAppender<TEnumerable, TElement> appender = enumerableShape.GetAppender();
return new Func<IConfiguration, TEnumerable?>(configuration =>
{
if (IsNullConfiguration(configuration))
{
return default;
}
TEnumerable enumerable = defaultCtor();
foreach (IConfigurationSection child in configuration.GetChildren())
{
TElement element = elementBinder(child);
appender(ref enumerable, element);
}
return enumerable;
});
case CollectionConstructionStrategy.Parameterized:
ParameterizedCollectionConstructor<TElement, TElement, TEnumerable> spanCtor = enumerableShape.GetParameterizedConstructor();
return new Func<IConfiguration, TEnumerable?>(configuration =>
{
if (IsNullConfiguration(configuration))
{
return default;
}
using var buffer = new PooledList<TElement>();
foreach (IConfigurationSection child in configuration.GetChildren())
{
TElement element = elementBinder(child);
buffer.Add(element);
}
return spanCtor(buffer.AsSpan());
});
default:
return CreateNotSupportedBinder<TEnumerable>();
}
}
public override object? VisitDictionary<TDictionary, TKey, TValue>(IDictionaryTypeShape<TDictionary, TKey, TValue> dictionaryShape, object? state = null)
{
if (!s_builtInParsers.TryGetValue(typeof(TKey), out object? parser))
{
throw new NotSupportedException($"Dictionary keys of type '{typeof(TKey)}' are not supported.");
}
Func<IConfigurationSection, TKey> keyBinder = CreateKeyBinder((Func<string, TKey>)parser!);
Func<IConfiguration, TValue> valueBinder = GetOrAddBinder(dictionaryShape.ValueType)!;
switch (dictionaryShape.ConstructionStrategy)
{
case CollectionConstructionStrategy.Mutable:
MutableCollectionConstructor<TKey, TDictionary> defaultCtor = dictionaryShape.GetDefaultConstructor();
var inserter = dictionaryShape.GetInserter();
return new Func<IConfiguration, TDictionary?>(configuration =>
{
if (IsNullConfiguration(configuration))
{
return default;
}
TDictionary dict = defaultCtor();
foreach (IConfigurationSection section in configuration.GetChildren())
{
if (section.Key is TypeDiscriminator)
{
continue;
}
inserter(ref dict, keyBinder(section), valueBinder(section));
}
return dict;
});
case CollectionConstructionStrategy.Parameterized:
ParameterizedCollectionConstructor<TKey, KeyValuePair<TKey, TValue>, TDictionary> spanCtor = dictionaryShape.GetParameterizedConstructor();
var duplicateKeyValidator = dictionaryShape.CreateDuplicateKeyValidator();
return new Func<IConfiguration, TDictionary?>(configuration =>
{
if (IsNullConfiguration(configuration))
{
return default;
}
using var buffer = new PooledList<KeyValuePair<TKey, TValue>>();
foreach (IConfigurationSection section in configuration.GetChildren())
{
if (section.Key is TypeDiscriminator)
{
continue;
}
KeyValuePair<TKey, TValue> entry = new(keyBinder(section), valueBinder(section));
buffer.Add(entry);
}
var span = buffer.AsSpan();
var finalDict = spanCtor(span);
duplicateKeyValidator.ValidatePotentialDuplicates(finalDict, span);
return finalDict;
});
default:
return CreateNotSupportedBinder<TDictionary>();
}
}
public override object? VisitSurrogate<T, TSurrogate>(ISurrogateTypeShape<T, TSurrogate> surrogateShape, object? state = null)
{
Func<IConfiguration, TSurrogate?> surrogateBinder = GetOrAddBinder(surrogateShape.SurrogateType);
var marshaler = surrogateShape.Marshaler;
return new Func<IConfiguration, T?>(configuration => marshaler.Unmarshal(surrogateBinder(configuration)));
}
public override object? VisitOptional<TOptional, TElement>(IOptionalTypeShape<TOptional, TElement> optionalShape, object? state = null)
{
Func<IConfiguration, TElement?> elementBinder = GetOrAddBinder(optionalShape.ElementType);
var createNone = optionalShape.GetNoneConstructor();
var createSome = optionalShape.GetSomeConstructor();
return new Func<IConfiguration, TOptional>(configuration => IsNullConfiguration(configuration) ? createNone() : createSome(elementBinder(configuration)!));
}
public override object? VisitEnum<TEnum, TUnderlying>(IEnumTypeShape<TEnum, TUnderlying> enumShape, object? state = null)
{
#if NET
return CreateValueBinder(Enum.Parse<TEnum>);
#else
return CreateValueBinder(text => (TEnum)Enum.Parse(typeof(TEnum), text));
#endif
}
public override object? VisitUnion<TUnion>(IUnionTypeShape<TUnion> unionShape, object? state = null)
{
var baseTypeBinder = (Func<IConfiguration, TUnion>)unionShape.BaseType.Invoke(this)!;
var unionCaseBinders = unionShape.UnionCases
.Select(unionCase => (Func<IConfiguration, TUnion>)unionCase.Accept(this, null)!)
.ToArray();
var discriminatorLookup = unionShape.UnionCases.ToDictionary(c => c.Name, c => c.Index);
return new Func<IConfiguration, TUnion?>(configuration =>
{
if (IsNullConfiguration(configuration))
{
return default;
}
IConfigurationSection discriminator = configuration.GetSection(TypeDiscriminator);
var polymorphicBinder = discriminator.Value is not null && discriminatorLookup.TryGetValue(discriminator.Value, out int index)
? unionCaseBinders[index]
: baseTypeBinder;
return polymorphicBinder(configuration);
});
}
public override object? VisitUnionCase<TUnionCase, TUnion>(IUnionCaseShape<TUnionCase, TUnion> unionCaseShape, object? state = null)
{
var caseBinder = (Func<IConfiguration, TUnion>)unionCaseShape.UnionCaseType.Accept(this)!;
if (unionCaseShape.UnionCaseType is IObjectTypeShape or IDictionaryTypeShape)
{
return caseBinder;
}
// Non-object schemas nest the case value under the $values property.
return new Func<IConfiguration, TUnion>(cfg => cfg.GetSection(ValuesProperty) is { } section ? caseBinder(section) : default!);
}
public override object? VisitFunction<TFunction, TArgumentState, TResult>(IFunctionTypeShape<TFunction, TArgumentState, TResult> functionShape, object? state = null)
{
return CreateNotSupportedBinder<TFunction>();
}
private static IEnumerable<KeyValuePair<Type, object>> GetBuiltInParsers()
{
yield return Create(bool.Parse);
yield return Create(text => byte.Parse(text, NumberStyles.Integer, CultureInfo.InvariantCulture));
yield return Create(text => ushort.Parse(text, NumberStyles.Integer, CultureInfo.InvariantCulture));
yield return Create(text => uint.Parse(text, NumberStyles.Integer, CultureInfo.InvariantCulture));
yield return Create(text => ulong.Parse(text, NumberStyles.Integer, CultureInfo.InvariantCulture));
yield return Create(text => sbyte.Parse(text, NumberStyles.Integer, CultureInfo.InvariantCulture));
yield return Create(text => short.Parse(text, NumberStyles.Integer, CultureInfo.InvariantCulture));
yield return Create(text => int.Parse(text, NumberStyles.Integer, CultureInfo.InvariantCulture));
yield return Create(text => long.Parse(text, NumberStyles.Integer, CultureInfo.InvariantCulture));
yield return Create(text => BigInteger.Parse(text, NumberStyles.Integer, CultureInfo.InvariantCulture));
yield return Create(text => float.Parse(text, NumberStyles.Float, CultureInfo.InvariantCulture));
yield return Create(text => double.Parse(text, NumberStyles.Float, CultureInfo.InvariantCulture));
yield return Create(text => decimal.Parse(text, NumberStyles.Float, CultureInfo.InvariantCulture));
yield return Create<string?>(text => text);
yield return Create(char.Parse);
yield return Create(Guid.Parse);
yield return Create(text => TimeSpan.Parse(text, CultureInfo.InvariantCulture));
yield return Create(text => DateTime.Parse(text, CultureInfo.InvariantCulture));
yield return Create(text => DateTimeOffset.Parse(text, CultureInfo.InvariantCulture));
yield return Create(text => new Uri(text, UriKind.RelativeOrAbsolute));
yield return Create(Version.Parse);
yield return Create(Convert.FromBase64String);
#if NET
yield return Create(text => UInt128.Parse(text, NumberStyles.Integer, CultureInfo.InvariantCulture));
yield return Create(text => Int128.Parse(text, NumberStyles.Integer, CultureInfo.InvariantCulture));
yield return Create(text => Half.Parse(text, NumberStyles.Float, CultureInfo.InvariantCulture));
yield return Create(text => DateOnly.Parse(text, CultureInfo.InvariantCulture));
yield return Create(text => TimeOnly.Parse(text, CultureInfo.InvariantCulture));
yield return Create(text => System.Text.Rune.GetRuneAt(text, 0));
#endif
yield return Create<object?>(text =>
bool.TryParse(text, out bool boolResult) ? boolResult :
int.TryParse(text, out int intResult) ? intResult :
double.TryParse(text, out double doubleResult) ? doubleResult :
text);
static KeyValuePair<Type, object> Create<T>(Func<string, T> parser)
=> new(typeof(T), parser);
}
private static Func<IConfigurationSection, T> CreateKeyBinder<T>(Func<string, T> parser)
{
return configuration =>
{
try
{
return parser(configuration.Key);
}
catch (Exception e)
{
throw new InvalidOperationException($"Failed to convert configuration key at '{configuration.Path}' to type '{typeof(T)}'.", e);
}
};
}
private static Func<IConfiguration, T> CreateValueBinder<T>(Func<string, T> parser)
{
return configuration =>
{
if (configuration is not IConfigurationSection section)
{
throw new InvalidOperationException();
}
if (section.Value is null && default(T) is null)
{
return default!;
}
try
{
return parser(section.Value!);
}
catch (Exception e)
{
throw new InvalidOperationException($"Failed to convert configuration value at '{section.Path}' to type '{typeof(T)}'.", e);
}
};
}
private static Func<IConfiguration, T> CreateNotSupportedBinder<T>() =>
config => IsNullConfiguration(config) ? default! : throw new NotSupportedException($"Type '{typeof(T)}' is not supported.");
private static bool IsNullConfiguration(IConfiguration configuration) =>
configuration is IConfigurationSection { Value: null } &&
!configuration.GetChildren().Any();
}
private sealed class DelayedConfigurationBinderFactory : IDelayedValueFactory
{
public DelayedValue Create<T>(ITypeShape<T> typeShape) =>
new DelayedValue<Func<IConfiguration, T?>>(self => c => self.Result(c));
}
}