-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathCommandScanner.cs
More file actions
409 lines (334 loc) · 16 KB
/
Copy pathCommandScanner.cs
File metadata and controls
409 lines (334 loc) · 16 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
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.Extensions.Logging;
namespace SampSharp.Entities.SAMP.Commands;
/// <summary>
/// Scans ISystem types for command methods marked with [PlayerCommand] or [ConsoleCommand].
/// Builds CommandDefinition objects and registers them in a registry.
/// </summary>
internal partial class CommandScanner(ISystemRegistry systemRegistry, IUnhandledExceptionHandler unhandledExceptionHandler, ILogger logger)
{
private static readonly MethodInfo _getComponentInfo = typeof(IEntityManager).GetMethod(nameof(IEntityManager.GetComponent),
BindingFlags.Public | BindingFlags.Instance, null, [typeof(EntityId)], null)!;
private readonly ISystemRegistry _systemRegistry = systemRegistry;
private readonly IUnhandledExceptionHandler _unhandledExceptionHandler = unhandledExceptionHandler;
private readonly ILogger _logger = logger;
public void ScanPlayerCommands(CommandRegistry registry, ICommandParameterParserFactory parserFactory)
{
var scanner = ClassScanner.Create().IncludeTypes(_systemRegistry.GetSystemTypes().Span).IncludeNonPublicMembers();
var methods = scanner.ScanMethods<PlayerCommandAttribute>();
foreach (var (systemType, method, attribute) in methods)
{
var classGroups = systemType.GetCustomAttributes<CommandGroupAttribute>();
var methodGroups = method.GetCustomAttributes<CommandGroupAttribute>();
var commandGroup = BuildCommandGroup(classGroups, methodGroups);
var commandName = attribute.Name ?? GetCommandName(method);
if (string.IsNullOrWhiteSpace(commandName) || commandName.Contains(' '))
{
LogRejectedCommand("player", systemType, method,
$"invalid command name '{commandName ?? "<null>"}'. Command names must not be empty or contain spaces.");
continue;
}
var parameters = method.GetParameters();
if (parameters.Length == 0 || (!parameters[0].ParameterType.IsAssignableTo(typeof(Component)) && parameters[0].ParameterType != typeof(EntityId)))
{
LogRejectedCommand("player", systemType, method, "the first parameter must be a Component or EntityId.");
continue;
}
var aliases = method.GetCustomAttributes<AliasAttribute>().SelectMany(a => a.Aliases).Select(a => new CommandAlias(a)).ToArray();
var tags = method.GetCustomAttributes<CommandTagAttribute>().Select(t => new CommandTag(t.Key, t.Value)).ToArray();
if (!TryBuildOverload(commandName, commandGroup, method, systemType, parserFactory, 1, aliases, tags, out var overload, out var rejectionReason))
{
LogRejectedCommand("player", systemType, method, rejectionReason!);
continue;
}
registry.Register(overload);
}
}
public void ScanConsoleCommands(CommandRegistry registry, ICommandParameterParserFactory parserFactory)
{
var scanner = ClassScanner.Create().IncludeTypes(_systemRegistry.GetSystemTypes().Span).IncludeNonPublicMembers();
var methods = scanner.ScanMethods<ConsoleCommandAttribute>();
foreach (var (systemType, method, attribute) in methods)
{
var classGroups = systemType.GetCustomAttributes<CommandGroupAttribute>();
var methodGroups = method.GetCustomAttributes<CommandGroupAttribute>();
var commandGroup = BuildCommandGroup(classGroups, methodGroups);
var commandName = attribute.Name ?? GetCommandName(method);
if (string.IsNullOrWhiteSpace(commandName) || commandName.Contains(' '))
{
LogRejectedCommand("console", systemType, method,
$"invalid command name '{commandName ?? "<null>"}'. Command names must not be empty or contain spaces.");
continue;
}
var aliases = method.GetCustomAttributes<AliasAttribute>().SelectMany(a => a.Aliases).Select(a => new CommandAlias(a)).ToArray();
var tags = method.GetCustomAttributes<CommandTagAttribute>().Select(t => new CommandTag(t.Key, t.Value)).ToArray();
var prefixParams = 0;
var parameters = method.GetParameters();
if (parameters.Length > 0 && parameters[0].ParameterType == typeof(ConsoleCommandDispatchContext))
{
prefixParams = 1;
}
if (!TryBuildOverload(commandName, commandGroup, method, systemType, parserFactory, prefixParams, aliases, tags, out var overload, out var rejectionReason))
{
LogRejectedCommand("console", systemType, method, rejectionReason!);
continue;
}
registry.Register(overload);
}
}
private CommandGroup? BuildCommandGroup(IEnumerable<CommandGroupAttribute> classGroups, IEnumerable<CommandGroupAttribute> methodGroups)
{
var allParts = classGroups.SelectMany(g => g.Parts).Concat(methodGroups.SelectMany(g => g.Parts)).ToList();
return allParts.Count > 0 ? new CommandGroup(allParts) : null;
}
private bool TryBuildOverload(string commandName, CommandGroup? commandGroup, MethodInfo method, Type systemType, ICommandParameterParserFactory parserFactory,
int prefixParameters, CommandAlias[] aliases, CommandTag[] tags, [NotNullWhen(true)] out CommandDefinition? overload, [NotNullWhen(false)] out string? rejectionReason)
{
overload = null;
rejectionReason = null;
var parameters = method.GetParameters();
if (parameters.Length < prefixParameters)
{
rejectionReason = "the command signature is missing required dispatch context parameters.";
return false;
}
// Validate return type: bool, int, void, Task, Task<T>
if (!IsValidReturnType(method.ReturnType))
{
rejectionReason = $"invalid return type '{method.ReturnType}'. Supported return types are void, bool, Task, and Task<bool>.";
return false;
}
// Collect parsed parameters (skip prefix, handle DI)
if (!TryCollectParameters(parameters, prefixParameters, parserFactory, out var parsedParams, out rejectionReason))
{
return false;
}
var parameterSources = BuildMethodParameterSources(parameters, prefixParameters, parsedParams!);
var invoker = CompileCommandInvoker(method, parameterSources);
var componentMatcher = CompileComponentMatcher(parameterSources, prefixParameters);
overload = new CommandDefinition(commandName, commandGroup, method, parameters, systemType, parsedParams!, invoker, prefixParameters, aliases, tags, componentMatcher);
return true;
}
private static MethodParameterSource[] BuildMethodParameterSources(ParameterInfo[] parameters, int prefixParameterCount, CommandParameterInfo[] parsedParameters)
{
var sources = new MethodParameterSource[parameters.Length];
var parsedParamsByIndex = parsedParameters.ToDictionary(p => p.ParameterIndex);
var j = 0; // Counter for args array index
for (var i = 0; i < parameters.Length; i++)
{
var paramInfo = parameters[i];
var source = new MethodParameterSource(paramInfo);
// Check if this is a prefix parameter (Player component or ConsoleCommandDispatchContext)
if (i < prefixParameterCount)
{
source.ParameterIndex = j++;
}
// Check if this is a parsed parameter
else if (parsedParamsByIndex.ContainsKey(i))
{
source.ParameterIndex = j++;
}
else
{
// This is a DI service parameter
source.IsService = true;
}
// Mark as component if applicable
if (paramInfo.ParameterType.IsAssignableTo(typeof(Component)))
{
source.IsComponent = true;
}
sources[i] = source;
}
return sources;
}
private CommandInvoker CompileCommandInvoker(MethodInfo method, MethodParameterSource[] sources)
{
var methodInvoker = MethodInvokerFactory.Compile(method, sources, MethodResult.False);
return ToCommandInvoker(methodInvoker, method);
}
private static CommandComponentMatcher CompileComponentMatcher(MethodParameterSource[] sources, int prefixParameterCount)
{
var componentSources = sources.Where(s => s.IsComponent && s.ParameterIndex >= 0).ToArray();
if (componentSources.Length == 0)
{
return (_, _, _) => true;
}
var prefixArgs = Expression.Parameter(typeof(object[]), "prefixArgs");
var parsedArgs = Expression.Parameter(typeof(object[]), "parsedArgs");
var entityManager = Expression.Parameter(typeof(IEntityManager), "entityManager");
var entityEmpty = Expression.Constant(EntityId.Empty, typeof(EntityId));
Expression? body = null;
foreach (var source in componentSources)
{
var sourceArgs = source.ParameterIndex < prefixParameterCount ? prefixArgs : parsedArgs;
var sourceIndex = source.ParameterIndex < prefixParameterCount
? source.ParameterIndex
: source.ParameterIndex - prefixParameterCount;
var entityValue = Expression.ArrayIndex(sourceArgs, Expression.Constant(sourceIndex));
var entity = Expression.Convert(entityValue, typeof(EntityId));
var componentType = source.Info.ParameterType;
var component = Expression.Condition(
Expression.Equal(entity, entityEmpty),
Expression.Constant(null, componentType),
Expression.Call(entityManager, _getComponentInfo.MakeGenericMethod(componentType), entity));
var check = Expression.OrElse(
Expression.Equal(entity, entityEmpty),
Expression.NotEqual(component, Expression.Constant(null, componentType)));
body = body == null ? check : Expression.AndAlso(body, check);
}
return Expression.Lambda<CommandComponentMatcher>(body!, prefixArgs, parsedArgs, entityManager).Compile();
}
private CommandInvoker ToCommandInvoker(MethodInvoker methodInvoker, MethodInfo method)
{
if (method.ReturnType == typeof(void) )
{
return [StackTraceHidden](target, args, services, manager) =>
{
var result = (MethodResult?)methodInvoker(target, args, services, manager);
return result?.Value ?? true;
};
}
if (method.ReturnType == typeof(bool))
{
return [StackTraceHidden] (target, args, services, manager) => ((MethodResult)methodInvoker(target, args, services, manager)!).Value;
}
if (method.ReturnType == typeof(Task))
{
return [StackTraceHidden](target, args, services, manager) =>
{
var result = methodInvoker(target, args, services, manager)!;
if (result is Task task)
{
HandleTask(task);
return true;
}
if (result is MethodResult methodResult)
{
return methodResult.Value;
}
return true;
};
}
if (method.ReturnType == typeof(Task<bool>))
{
return [StackTraceHidden](target, args, services, manager) =>
{
var result = methodInvoker(target, args, services, manager)!;
if (result is Task<bool> task)
{
if (task.IsCompleted)
{
return task.Result;
}
HandleTask(task);
return true;
}
if (result is MethodResult methodResult)
{
return methodResult.Value;
}
return true;
};
}
throw new InvalidOperationException();
}
private void HandleTask(Task task)
{
if (task.IsCompleted)
{
HandleTaskException(task);
}
else
{
task.ContinueWith(HandleTaskException);
}
}
private void HandleTaskException(Task task)
{
if (task is { IsFaulted: true, Exception: not null })
{
// Exception from async task - would typically be logged
if (task.Exception.InnerExceptions.Count == 1)
{
_unhandledExceptionHandler.Handle("async-command", task.Exception.InnerExceptions[0]);
}
else
{
_unhandledExceptionHandler.Handle("async-command", task.Exception);
}
}
}
private static bool IsValidReturnType(Type returnType)
{
return returnType == typeof(void) ||
returnType == typeof(bool) ||
returnType == typeof(Task) ||
returnType == typeof(Task<bool>);
}
private static bool TryCollectParameters(ParameterInfo[] parameters, int prefixParameters, ICommandParameterParserFactory parserFactory,
out CommandParameterInfo[]? result, [NotNullWhen(false)] out string? rejectionReason)
{
result = null;
rejectionReason = null;
if (parameters.Length < prefixParameters)
{
rejectionReason = "the command signature is missing required dispatch context parameters.";
return false;
}
var list = new List<CommandParameterInfo>();
var parameterIndex = prefixParameters;
var optionalSeen = false;
for (var i = prefixParameters; i < parameters.Length; i++)
{
var param = parameters[i];
var paramAtribute = param.GetCustomAttribute<CommandParameterAttribute>();
var paramName = paramAtribute?.Name ?? param.Name ?? $"param{i}";
// Try to get a parser for this parameter
var parserInstance = paramAtribute?.ParserType is not null
? Activator.CreateInstance(paramAtribute.ParserType)
: null;
var parser = parserInstance as ICommandParameterParser ?? parserFactory.CreateParser(parameters, i);
if (parser == null)
{
// No parser = this is a DI parameter, not parsed from input
parameterIndex++;
continue;
}
// This parameter will be parsed from input
var isRequired = !param.HasDefaultValue;
if (!isRequired && !optionalSeen)
{
optionalSeen = true;
}
else if (isRequired && optionalSeen)
{
// Required parameter after optional - invalid
rejectionReason = "required parameters cannot follow optional parameters.";
return false;
}
var cmdParamInfo = new CommandParameterInfo(paramName, parser, isRequired, param.DefaultValue, parameterIndex++);
list.Add(cmdParamInfo);
}
result = list.ToArray();
return true;
}
private static string GetCommandName(MethodInfo method)
{
var name = method.Name.ToLowerInvariant();
if (name.EndsWith("command", StringComparison.Ordinal))
{
name = name[..^7];
}
return name;
}
private void LogRejectedCommand(string commandKind, Type systemType, MethodInfo method, string reason)
{
LogRejectedCommand(commandKind, systemType.FullName ?? systemType.Name, method.Name, reason);
}
[LoggerMessage(LogLevel.Warning, "Rejected {CommandKind} command {SystemType}.{Method}: {Reason}")]
private partial void LogRejectedCommand(string commandKind, string systemType, string method, string reason);
}