-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathUtilities.cs
More file actions
802 lines (673 loc) · 32 KB
/
Utilities.cs
File metadata and controls
802 lines (673 loc) · 32 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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
#pragma warning disable IDE0051 // Remove unused private members
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;
using Ultz.Extensions.Commands.Attributes;
using Ultz.Extensions.Commands.Attributes.Checks;
using Ultz.Extensions.Commands.Attributes.Commands;
using Ultz.Extensions.Commands.Attributes.Commands.Cooldown;
using Ultz.Extensions.Commands.Attributes.Modules;
using Ultz.Extensions.Commands.Attributes.Parameters;
using Ultz.Extensions.Commands.Builders;
using Ultz.Extensions.Commands.Mapping;
using Ultz.Extensions.Commands.ModuleBases;
using Ultz.Extensions.Commands.Parsing.ArgumentParsers;
using Ultz.Extensions.Commands.Parsing.TypeParsers;
using Ultz.Extensions.Commands.Parsing.TypeParsers.Primitive;
using Ultz.Extensions.Commands.Results.Failed.Execution;
using Ultz.Extensions.Commands.Results.User;
namespace Ultz.Extensions.Commands
{
internal static class Utilities
{
private static readonly MethodInfo _getGenericTaskResultMethodInfo = typeof(Utilities)
.GetMethod(nameof(GetGenericTaskResult), BindingFlags.Static | BindingFlags.NonPublic);
private static readonly MethodInfo _getGenericValueTaskResultMethodInfo = typeof(Utilities)
.GetMethod(nameof(GetGenericValueTaskResult), BindingFlags.Static | BindingFlags.NonPublic);
public static readonly IReadOnlyDictionary<Type, Delegate> TryParseDelegates;
static Utilities()
{
#if NETSTANDARD2_0
TryParseDelegates = new Dictionary<Type, Delegate>(13)
{
[typeof(char)] = (TryParseDelegate<char>) TryParseChar,
[typeof(bool)] = (TryParseDelegate<bool>) TryParseBool,
[typeof(byte)] = (TryParseDelegate<byte>) TryParseByte,
[typeof(sbyte)] = (TryParseDelegate<sbyte>) TryParseSByte,
[typeof(short)] = (TryParseDelegate<short>) TryParseShort,
[typeof(ushort)] = (TryParseDelegate<ushort>) TryParseUShort,
[typeof(int)] = (TryParseDelegate<int>) TryParseInt,
[typeof(uint)] = (TryParseDelegate<uint>) TryParseUInt,
[typeof(long)] = (TryParseDelegate<long>) TryParseLong,
[typeof(ulong)] = (TryParseDelegate<ulong>) TryParseULong,
[typeof(float)] = (TryParseDelegate<float>) TryParseFloat,
[typeof(double)] = (TryParseDelegate<double>) TryParseDouble,
[typeof(decimal)] = (TryParseDelegate<decimal>) TryParseDecimal
};
#else
TryParseDelegates = new Dictionary<Type, Delegate>(13)
{
[typeof(char)] = (TryParseDelegate<char>) TryParseChar,
[typeof(bool)] = (TryParseDelegate<bool>) bool.TryParse,
[typeof(byte)] = (TryParseDelegate<byte>) byte.TryParse,
[typeof(sbyte)] = (TryParseDelegate<sbyte>) sbyte.TryParse,
[typeof(short)] = (TryParseDelegate<short>) short.TryParse,
[typeof(ushort)] = (TryParseDelegate<ushort>) ushort.TryParse,
[typeof(int)] = (TryParseDelegate<int>) int.TryParse,
[typeof(uint)] = (TryParseDelegate<uint>) uint.TryParse,
[typeof(long)] = (TryParseDelegate<long>) long.TryParse,
[typeof(ulong)] = (TryParseDelegate<ulong>) ulong.TryParse,
[typeof(float)] = (TryParseDelegate<float>) float.TryParse,
[typeof(double)] = (TryParseDelegate<double>) double.TryParse,
[typeof(decimal)] = (TryParseDelegate<decimal>) decimal.TryParse
};
#endif
}
#if NETSTANDARD2_0
private static bool TryParseBool(ReadOnlySpan<char> span, out bool result) =>
bool.TryParse(span.ToString(), out result);
private static bool TryParseByte(ReadOnlySpan<char> span, out byte result) =>
byte.TryParse(span.ToString(), out result);
private static bool TryParseSByte(ReadOnlySpan<char> span, out sbyte result) =>
sbyte.TryParse(span.ToString(), out result);
private static bool TryParseShort(ReadOnlySpan<char> span, out short result) =>
short.TryParse(span.ToString(), out result);
private static bool TryParseUShort(ReadOnlySpan<char> span, out ushort result) =>
ushort.TryParse(span.ToString(), out result);
private static bool TryParseInt(ReadOnlySpan<char> span, out int result) =>
int.TryParse(span.ToString(), out result);
private static bool TryParseUInt(ReadOnlySpan<char> span, out uint result) =>
uint.TryParse(span.ToString(), out result);
private static bool TryParseLong(ReadOnlySpan<char> span, out long result) =>
long.TryParse(span.ToString(), out result);
private static bool TryParseULong(ReadOnlySpan<char> span, out ulong result) =>
ulong.TryParse(span.ToString(), out result);
private static bool TryParseFloat(ReadOnlySpan<char> span, out float result) =>
float.TryParse(span.ToString(), out result);
private static bool TryParseDouble(ReadOnlySpan<char> span, out double result) =>
double.TryParse(span.ToString(), out result);
private static bool TryParseDecimal(ReadOnlySpan<char> span, out decimal result) =>
decimal.TryParse(span.ToString(), out result);
#endif
public static bool IsValidModuleDefinition(TypeInfo typeInfo)
{
return typeof(IModuleBase).IsAssignableFrom(typeInfo) && !typeInfo.IsAbstract &&
!typeInfo.ContainsGenericParameters;
}
public static bool IsValidTypeParserDefinition(Type parserType, Type parameterType)
{
if (!typeof(ITypeParser).IsAssignableFrom(parserType) || parserType.IsAbstract)
{
return false;
}
var baseType = parserType.BaseType;
while (!baseType.IsGenericType || baseType.GetGenericTypeDefinition() != typeof(TypeParser<>))
{
baseType = baseType.BaseType;
}
return Array.Exists(baseType.GetGenericArguments(), x => x == parameterType);
}
public static bool IsValidArgumentParserDefinition(Type parserType)
{
return typeof(IArgumentParser).IsAssignableFrom(parserType) && !parserType.IsAbstract;
}
public static bool IsNullable(Type type)
{
return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
}
public static Type MakeNullable(Type type)
{
return typeof(Nullable<>).MakeGenericType(type);
}
public static IEnumerable<TypeInfo> GetValidModules(TypeInfo typeInfo)
{
var nestedTypes = typeInfo.GetNestedTypes();
for (var i = 0; i < nestedTypes.Length; i++)
{
var nestedTypeInfo = nestedTypes[i].GetTypeInfo();
if (IsValidModuleDefinition(nestedTypeInfo))
{
yield return nestedTypeInfo;
}
}
}
public static IEnumerable<MethodInfo> GetValidCommands(TypeInfo typeInfo)
{
return typeInfo.DeclaredMethods.Where(x => x.GetCustomAttribute<CommandAttribute>() != null);
}
public static ModuleBuilder CreateModuleBuilder(CommandService service, ModuleBuilder parent, TypeInfo typeInfo)
{
if (!IsValidModuleDefinition(typeInfo))
{
throw new ArgumentException(
$"{typeInfo} must not be abstract, must not have generic parameters, and must inherit ModuleBase.",
nameof(typeInfo));
}
var builder = new ModuleBuilder(typeInfo, parent);
var attributes = typeInfo.GetCustomAttributes(false);
for (var i = 0; i < attributes.Length; i++)
{
switch (attributes[i])
{
case NameAttribute nameAttribute:
builder.WithName(nameAttribute.Value);
break;
case DescriptionAttribute descriptionAttribute:
builder.WithDescription(descriptionAttribute.Value);
break;
case RemarksAttribute remarksAttribute:
builder.WithRemarks(remarksAttribute.Value);
break;
case RunModeAttribute runModeAttribute:
builder.WithRunMode(runModeAttribute.Value);
break;
case IgnoresExtraArgumentsAttribute ignoreExtraArgumentsAttribute:
builder.WithIgnoresExtraArguments(ignoreExtraArgumentsAttribute.Value);
break;
case OverrideArgumentParserAttribute overrideArgumentParserAttribute:
builder.WithCustomArgumentParserType(overrideArgumentParserAttribute.Value);
if (overrideArgumentParserAttribute.GetType() != typeof(OverrideArgumentParserAttribute))
{
builder.AddAttribute(overrideArgumentParserAttribute);
}
break;
case GroupAttribute groupAttribute:
for (var j = 0; j < groupAttribute.Aliases.Length; j++)
{
builder.AddAlias(groupAttribute.Aliases[j]);
}
break;
case CheckAttribute checkAttribute:
builder.AddCheck(checkAttribute);
break;
case DisabledAttribute disabledAttribute:
builder.WithIsEnabled(!disabledAttribute.Value);
break;
case Attribute attribute:
builder.AddAttribute(attribute);
break;
}
}
foreach (var command in GetValidCommands(typeInfo))
{
if (!command.IsPublic || command.IsStatic || command.IsGenericMethod)
{
throw new ArgumentException(
$"{command} must not be non-public, static, and must not be a generic method.");
}
builder.Commands.Add(CreateCommandBuilder(service, builder, typeInfo, command));
}
foreach (var submodule in GetValidModules(typeInfo))
{
builder.Submodules.Add(CreateModuleBuilder(service, builder, submodule));
}
return builder;
}
public static CommandBuilder CreateCommandBuilder(CommandService service, ModuleBuilder module,
TypeInfo typeInfo, MethodInfo methodInfo)
{
var builder = new CommandBuilder(module, CreateModuleBaseCommandCallback(service, typeInfo, methodInfo));
var attributes = methodInfo.GetCustomAttributes(false);
for (var i = 0; i < attributes.Length; i++)
{
switch (attributes[i])
{
case NameAttribute nameAttribute:
builder.WithName(nameAttribute.Value);
break;
case DescriptionAttribute descriptionAttribute:
builder.WithDescription(descriptionAttribute.Value);
break;
case RemarksAttribute remarksAttribute:
builder.WithRemarks(remarksAttribute.Value);
break;
case PriorityAttribute priorityAttribute:
builder.WithPriority(priorityAttribute.Value);
break;
case RunModeAttribute runModeAttribute:
builder.WithRunMode(runModeAttribute.Value);
break;
case CooldownAttribute cooldownAttribute:
builder.AddCooldown(new Cooldown.Cooldown(cooldownAttribute.Amount, cooldownAttribute.Per,
cooldownAttribute.BucketType));
break;
case IgnoresExtraArgumentsAttribute ignoreExtraArgumentsAttribute:
builder.WithIgnoresExtraArguments(ignoreExtraArgumentsAttribute.Value);
break;
case OverrideArgumentParserAttribute overrideArgumentParserAttribute:
builder.WithCustomArgumentParserType(overrideArgumentParserAttribute.Value);
if (overrideArgumentParserAttribute.GetType() != typeof(OverrideArgumentParserAttribute))
{
builder.AddAttribute(overrideArgumentParserAttribute);
}
break;
case CommandAttribute commandAttribute:
for (var j = 0; j < commandAttribute.Aliases.Length; j++)
{
builder.AddAlias(commandAttribute.Aliases[j]);
}
break;
case CheckAttribute checkAttribute:
builder.AddCheck(checkAttribute);
break;
case DisabledAttribute disabledAttribute:
builder.WithIsEnabled(!disabledAttribute.Value);
break;
case Attribute attribute:
builder.AddAttribute(attribute);
break;
}
}
var parameters = methodInfo.GetParameters();
for (var i = 0; i < parameters.Length; i++)
{
builder.Parameters.Add(CreateParameterBuilder(builder, parameters[i], i + 1 == parameters.Length));
}
return builder;
}
public static ParameterBuilder CreateParameterBuilder(CommandBuilder command, ParameterInfo parameterInfo,
bool last)
{
var builder = new ParameterBuilder(parameterInfo.ParameterType, command);
var attributes = parameterInfo.GetCustomAttributes(false);
for (var i = 0; i < attributes.Length; i++)
{
switch (attributes[i])
{
case NameAttribute nameAttribute:
builder.WithName(nameAttribute.Value);
break;
case DescriptionAttribute descriptionAttribute:
builder.WithDescription(descriptionAttribute.Value);
break;
case RemarksAttribute remarksAttribute:
builder.WithRemarks(remarksAttribute.Value);
break;
case ParamArrayAttribute _:
if (!last)
{
throw new ParameterBuildingException(builder,
$"A params array parameter must be the last parameter in a command. Parameter: {parameterInfo.Name} in {parameterInfo.Member.Name} in {parameterInfo.Member.DeclaringType}.");
}
builder.WithIsMultiple(true);
builder.Type = parameterInfo.ParameterType.GetElementType();
break;
case RemainderAttribute _:
if (!last)
{
throw new ParameterBuildingException(builder,
$"A remainder parameter must be the last parameter in a command. Parameter: {parameterInfo.Name} in {parameterInfo.Member.Name} in {parameterInfo.Member.DeclaringType}.");
}
builder.WithIsRemainder(true);
break;
case OverrideTypeParserAttribute overrideTypeParserAttribute:
builder.WithCustomTypeParserType(overrideTypeParserAttribute.Value);
if (overrideTypeParserAttribute.GetType() != typeof(OverrideTypeParserAttribute))
{
builder.AddAttribute(overrideTypeParserAttribute);
}
break;
case ParameterCheckAttribute parameterCheckAttribute:
builder.AddCheck(parameterCheckAttribute);
break;
case Attribute attribute:
builder.AddAttribute(attribute);
break;
}
}
if (parameterInfo.HasDefaultValue)
{
builder.WithIsOptional(true)
.WithDefaultValue(parameterInfo.DefaultValue);
}
else if (builder.IsMultiple)
{
builder.WithIsOptional(true)
.WithDefaultValue(Array.CreateInstance(builder.Type, 0));
}
if (builder.Name == null)
{
builder.WithName(parameterInfo.Name);
}
return builder;
}
public static Func<CommandService, IServiceProvider, T> CreateProviderConstructor<T>(
CommandService commandService, Type type)
{
var constructors = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance);
if (constructors.Length == 0)
{
throw new InvalidOperationException($"{type} has no public non-static constructors.");
}
if (constructors.Length > 1)
{
throw new InvalidOperationException($"{type} has multiple public constructors.");
}
static object GetDependency(CommandService commandService, ConstructorInfo ctor, IServiceProvider provider,
Type serviceType)
{
if (serviceType == typeof(IServiceProvider) || serviceType == provider.GetType())
{
return provider;
}
if (serviceType == typeof(CommandService) || serviceType == typeof(ICommandService) ||
serviceType == commandService.GetType())
{
return commandService;
}
var service = provider.GetService(serviceType);
if (service != null)
{
return service;
}
throw new InvalidOperationException(
$"Failed to instantiate {ctor.DeclaringType}, dependency of type {serviceType} was not found.");
}
var constructor = constructors[0];
var parameters = constructor.GetParameters();
var arguments = new object[parameters.Length];
IList<PropertyInfo> propertiesToInject = new List<PropertyInfo>();
do
{
var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
for (var i = 0; i < properties.Length; i++)
{
var property = properties[i];
if (property.SetMethod != null && !property.SetMethod.IsStatic && property.SetMethod.IsPublic
&& property.GetCustomAttribute<DoNotInjectAttribute>() == null)
{
propertiesToInject.Add(property);
}
}
type = type.BaseType.GetTypeInfo();
} while (type != typeof(object));
propertiesToInject = (propertiesToInject as List<PropertyInfo>).ToArray();
return (commandService, provider) =>
{
for (var i = 0; i < parameters.Length; i++)
{
arguments[i] = GetDependency(commandService, constructor, provider, parameters[i].ParameterType);
}
T instance;
try
{
instance = (T) constructor.Invoke(arguments);
}
catch (Exception ex)
{
throw new InvalidOperationException(
$"Failed to instantiate {constructor.DeclaringType}. See the inner exception for more details.",
ex);
}
for (var i = 0; i < propertiesToInject.Count; i++)
{
var property = propertiesToInject[i];
property.SetValue(instance,
GetDependency(commandService, constructor, provider, property.PropertyType));
}
return instance;
};
}
private static async Task<CommandResult> GetGenericTaskResult<T>(Task<T> task) where T : CommandResult
{
return task != null ? await task.ConfigureAwait(false) as CommandResult : null;
}
private static async ValueTask<CommandResult> GetGenericValueTaskResult<T>(ValueTask<T> task)
where T : CommandResult
{
return await task.ConfigureAwait(false);
}
private static CallbackFunc<T> CreateFunc<T>(Expression body, params ParameterExpression[] parameters)
{
return Expression.Lambda<CallbackFunc<T>>(body, parameters).Compile();
}
private static object CreateDelegate(Type type, MethodInfo method)
{
var methodParameters = method.GetParameters();
var instance = Expression.Parameter(typeof(object));
var arguments = Expression.Parameter(typeof(object[]));
var parameters = new Expression[methodParameters.Length];
for (var i = 0; i < methodParameters.Length; i++)
{
parameters[i] = Expression.Convert(Expression.ArrayIndex(arguments, Expression.Constant(i)),
methodParameters[i].ParameterType);
}
var call = Expression.Call(Expression.Convert(instance, type), method, parameters);
if (method.ReturnType == typeof(void))
{
return Expression.Lambda<Action<object, object[]>>(call, instance, arguments).Compile();
}
if (!method.ReturnType.IsGenericType)
{
if (typeof(CommandResult).IsAssignableFrom(method.ReturnType))
{
return CreateFunc<CommandResult>(Expression.Convert(call, typeof(CommandResult)), instance,
arguments);
}
if (method.ReturnType == typeof(Task))
{
return CreateFunc<Task>(call, instance, arguments);
}
if (method.ReturnType == typeof(ValueTask))
{
return CreateFunc<ValueTask>(call, instance, arguments);
}
}
else
{
var genericDefinition = method.ReturnType.GetGenericTypeDefinition();
if (genericDefinition == typeof(Task<>))
{
return CreateFunc<Task<CommandResult>>(
Expression.Call(
_getGenericTaskResultMethodInfo.MakeGenericMethod(method.ReturnType
.GenericTypeArguments[0]), call), instance, arguments);
}
if (genericDefinition == typeof(ValueTask<>))
{
return CreateFunc<ValueTask<CommandResult>>(
Expression.Call(
_getGenericValueTaskResultMethodInfo.MakeGenericMethod(
method.ReturnType.GenericTypeArguments[0]), call), instance, arguments);
}
}
throw new ArgumentException($"Unsupported method return type: {method.ReturnType}.", nameof(method));
}
public static ModuleBaseCommandCallbackDelegate CreateModuleBaseCommandCallback(CommandService service,
Type type, MethodInfo method)
{
var callbackDelegate = CreateDelegate(type, method);
var constructor = CreateProviderConstructor<IModuleBase>(service, type);
return async context =>
{
var instance = constructor(service, context.ServiceProvider);
instance.Prepare(context);
var executeAfter = true;
try
{
try
{
await instance.BeforeExecutedAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
executeAfter = false;
return new ExecutionFailedResult(context.Command, CommandExecutionStep.BeforeExecuted, ex);
}
switch (callbackDelegate)
{
case CallbackFunc<Task> taskCallback:
{
await taskCallback(instance, context.InternalArguments).ConfigureAwait(false);
break;
}
case CallbackFunc<Task<CommandResult>> taskResultCallback:
{
return await taskResultCallback(instance, context.InternalArguments).ConfigureAwait(false);
}
case CallbackFunc<ValueTask> valueTaskCallback:
{
await valueTaskCallback(instance, context.InternalArguments).ConfigureAwait(false);
break;
}
case CallbackFunc<ValueTask<CommandResult>> valueTaskResultCallback:
{
return await valueTaskResultCallback(instance, context.InternalArguments)
.ConfigureAwait(false);
}
case Action<object, object[]> voidCallback:
{
voidCallback(instance, context.InternalArguments);
break;
}
case CallbackFunc<CommandResult> resultCallback:
{
return resultCallback(instance, context.InternalArguments);
}
}
return null;
}
finally
{
try
{
if (executeAfter)
{
await instance.AfterExecutedAsync().ConfigureAwait(false);
}
}
finally
{
if (instance is IDisposable disposable)
{
try
{
disposable.Dispose();
}
catch
{
}
}
#if NETCOREAPP3_0
if (instance is IAsyncDisposable asyncDisposable)
{
try
{
await asyncDisposable.DisposeAsync().ConfigureAwait(false);
}
catch { }
}
#endif
}
}
};
}
public static IPrimitiveTypeParser CreatePrimitiveTypeParser(Type type)
{
return Activator.CreateInstance(typeof(PrimitiveTypeParser<>)
.MakeGenericType(type)) as IPrimitiveTypeParser;
}
public static IPrimitiveTypeParser CreateEnumTypeParser(Type type, Type enumType, CommandService service)
{
return Activator.CreateInstance(typeof(EnumTypeParser<>).MakeGenericType(type), enumType, service) as
IPrimitiveTypeParser;
}
public static IPrimitiveTypeParser CreateNullableEnumTypeParser(Type type, IPrimitiveTypeParser enumTypeParser)
{
return Activator.CreateInstance(typeof(NullableEnumTypeParser<>).MakeGenericType(type), enumTypeParser) as
IPrimitiveTypeParser;
}
public static IPrimitiveTypeParser CreateNullablePrimitiveTypeParser(Type type,
IPrimitiveTypeParser primitiveTypeParser)
{
return Activator.CreateInstance(typeof(NullablePrimitiveTypeParser<>).MakeGenericType(type),
primitiveTypeParser) as IPrimitiveTypeParser;
}
public static ITypeParser CreateNullableTypeParser(Type nullableType, ITypeParser typeParser)
{
return Activator.CreateInstance(typeof(NullableTypeParser<>).MakeGenericType(nullableType), typeParser) as
ITypeParser;
}
private static bool TryParseChar(ReadOnlySpan<char> value, out char result)
{
if (value.Length == 1)
{
result = value[0];
return true;
}
result = default;
return false;
}
public static bool IsNumericType(Type type)
{
return type == typeof(byte)
|| type == typeof(sbyte)
|| type == typeof(short)
|| type == typeof(ushort)
|| type == typeof(int)
|| type == typeof(uint)
|| type == typeof(long)
|| type == typeof(ulong)
|| type == typeof(float)
|| type == typeof(double)
|| type == typeof(decimal);
}
public static bool IsStringType(Type type)
{
return type == typeof(string);
}
public static bool IsNumericOrStringType(Type type)
{
return IsNumericType(type) || IsStringType(type);
}
public static bool IsCaseSensitive(this StringComparison comparison)
{
switch (comparison)
{
case StringComparison.CurrentCulture:
case StringComparison.InvariantCulture:
case StringComparison.Ordinal:
return true;
case StringComparison.CurrentCultureIgnoreCase:
case StringComparison.InvariantCultureIgnoreCase:
case StringComparison.OrdinalIgnoreCase:
return false;
default:
throw new ArgumentOutOfRangeException(nameof(comparison));
}
}
public static ImmutableArray<T> TryMoveToImmutable<T>(this ImmutableArray<T>.Builder builder)
{
return builder.Capacity == builder.Count
? builder.MoveToImmutable()
: builder.ToImmutable();
}
private delegate T CallbackFunc<T>(object instance, object[] arguments);
internal sealed class CommandOverloadComparer : IComparer<CommandMatch>
{
public static readonly CommandOverloadComparer Instance = new CommandOverloadComparer();
private CommandOverloadComparer()
{
}
public int Compare(CommandMatch x, CommandMatch y)
{
var pathCompare = y.Path.Count.CompareTo(x.Path.Count);
if (pathCompare != 0)
{
return pathCompare;
}
var priorityCompare = y.Command.Priority.CompareTo(x.Command.Priority);
if (priorityCompare != 0)
{
return priorityCompare;
}
var parametersCompare = y.Command.Parameters.Count.CompareTo(x.Command.Parameters.Count);
return parametersCompare;
}
}
}
}