You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

ModuleClassBuilder.cs 12 kB

8 years ago
8 years ago
8 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. using System;
  2. using System.Linq;
  3. using System.Collections.Generic;
  4. using System.Reflection;
  5. using System.Threading.Tasks;
  6. using Discord.Commands.Builders;
  7. namespace Discord.Commands
  8. {
  9. internal static class ModuleClassBuilder
  10. {
  11. private static readonly TypeInfo _moduleTypeInfo = typeof(IModuleBase).GetTypeInfo();
  12. public static async Task<IReadOnlyList<TypeInfo>> SearchAsync(Assembly assembly, CommandService service)
  13. {
  14. bool IsLoadableModule(TypeInfo info)
  15. {
  16. return info.DeclaredMethods.Any(x => x.GetCustomAttribute<CommandAttribute>() != null) &&
  17. info.GetCustomAttribute<DontAutoLoadAttribute>() == null;
  18. }
  19. var result = new List<TypeInfo>();
  20. foreach (var typeInfo in assembly.DefinedTypes)
  21. {
  22. if (typeInfo.IsPublic || typeInfo.IsNestedPublic)
  23. {
  24. if (IsValidModuleDefinition(typeInfo) &&
  25. !typeInfo.IsDefined(typeof(DontAutoLoadAttribute)))
  26. {
  27. result.Add(typeInfo);
  28. }
  29. }
  30. else if (IsLoadableModule(typeInfo))
  31. {
  32. await service._cmdLogger.WarningAsync($"Class {typeInfo.FullName} is not public and cannot be loaded. To suppress this message, mark the class with {nameof(DontAutoLoadAttribute)}.");
  33. }
  34. }
  35. return result;
  36. }
  37. public static Task<Dictionary<Type, ModuleInfo>> BuildAsync(CommandService service, params TypeInfo[] validTypes) => BuildAsync(validTypes, service);
  38. public static async Task<Dictionary<Type, ModuleInfo>> BuildAsync(IEnumerable<TypeInfo> validTypes, CommandService service)
  39. {
  40. /*if (!validTypes.Any())
  41. throw new InvalidOperationException("Could not find any valid modules from the given selection");*/
  42. var topLevelGroups = validTypes.Where(x => x.DeclaringType == null);
  43. var subGroups = validTypes.Intersect(topLevelGroups);
  44. var builtTypes = new List<TypeInfo>();
  45. var result = new Dictionary<Type, ModuleInfo>();
  46. foreach (var typeInfo in topLevelGroups)
  47. {
  48. // TODO: This shouldn't be the case; may be safe to remove?
  49. if (result.ContainsKey(typeInfo.AsType()))
  50. continue;
  51. var module = new ModuleBuilder(service, null);
  52. BuildModule(module, typeInfo, service);
  53. BuildSubTypes(module, typeInfo.DeclaredNestedTypes, builtTypes, service);
  54. builtTypes.Add(typeInfo);
  55. result[typeInfo.AsType()] = module.Build(service);
  56. }
  57. await service._cmdLogger.DebugAsync($"Successfully built {builtTypes.Count} modules.").ConfigureAwait(false);
  58. return result;
  59. }
  60. private static void BuildSubTypes(ModuleBuilder builder, IEnumerable<TypeInfo> subTypes, List<TypeInfo> builtTypes, CommandService service)
  61. {
  62. foreach (var typeInfo in subTypes)
  63. {
  64. if (!IsValidModuleDefinition(typeInfo))
  65. continue;
  66. if (builtTypes.Contains(typeInfo))
  67. continue;
  68. builder.AddModule((module) =>
  69. {
  70. BuildModule(module, typeInfo, service);
  71. BuildSubTypes(module, typeInfo.DeclaredNestedTypes, builtTypes, service);
  72. });
  73. builtTypes.Add(typeInfo);
  74. }
  75. }
  76. private static void BuildModule(ModuleBuilder builder, TypeInfo typeInfo, CommandService service)
  77. {
  78. var attributes = typeInfo.GetCustomAttributes();
  79. foreach (var attribute in attributes)
  80. {
  81. switch (attribute)
  82. {
  83. case NameAttribute name:
  84. builder.Name = name.Text;
  85. break;
  86. case SummaryAttribute summary:
  87. builder.Summary = summary.Text;
  88. break;
  89. case RemarksAttribute remarks:
  90. builder.Remarks = remarks.Text;
  91. break;
  92. case AliasAttribute alias:
  93. builder.AddAliases(alias.Aliases);
  94. break;
  95. case GroupAttribute group:
  96. builder.Name = builder.Name ?? group.Prefix;
  97. builder.AddAliases(group.Prefix);
  98. break;
  99. case PreconditionAttribute precondition:
  100. builder.AddPrecondition(precondition);
  101. break;
  102. default:
  103. builder.AddAttributes(attribute);
  104. break;
  105. }
  106. }
  107. //Check for unspecified info
  108. if (builder.Aliases.Count == 0)
  109. builder.AddAliases("");
  110. if (builder.Name == null)
  111. builder.Name = typeInfo.Name;
  112. var validCommands = typeInfo.DeclaredMethods.Where(x => IsValidCommandDefinition(x));
  113. foreach (var method in validCommands)
  114. {
  115. builder.AddCommand((command) =>
  116. {
  117. BuildCommand(command, typeInfo, method, service);
  118. });
  119. }
  120. }
  121. private static void BuildCommand(CommandBuilder builder, TypeInfo typeInfo, MethodInfo method, CommandService service)
  122. {
  123. var attributes = method.GetCustomAttributes();
  124. foreach (var attribute in attributes)
  125. {
  126. switch (attribute)
  127. {
  128. case CommandAttribute command:
  129. builder.AddAliases(command.Text);
  130. builder.RunMode = command.RunMode;
  131. builder.Name = builder.Name ?? command.Text;
  132. break;
  133. case NameAttribute name:
  134. builder.Name = name.Text;
  135. break;
  136. case PriorityAttribute priority:
  137. builder.Priority = priority.Priority;
  138. break;
  139. case SummaryAttribute summary:
  140. builder.Summary = summary.Text;
  141. break;
  142. case RemarksAttribute remarks:
  143. builder.Remarks = remarks.Text;
  144. break;
  145. case AliasAttribute alias:
  146. builder.AddAliases(alias.Aliases);
  147. break;
  148. case PreconditionAttribute precondition:
  149. builder.AddPrecondition(precondition);
  150. break;
  151. default:
  152. builder.AddAttributes(attribute);
  153. break;
  154. }
  155. }
  156. if (builder.Name == null)
  157. builder.Name = method.Name;
  158. var parameters = method.GetParameters();
  159. int pos = 0, count = parameters.Length;
  160. foreach (var paramInfo in parameters)
  161. {
  162. builder.AddParameter((parameter) =>
  163. {
  164. BuildParameter(parameter, paramInfo, pos++, count, service);
  165. });
  166. }
  167. var createInstance = ReflectionUtils.CreateBuilder<IModuleBase>(typeInfo, service);
  168. async Task<IResult> ExecuteCallback(ICommandContext context, object[] args, IServiceProvider services, CommandInfo cmd)
  169. {
  170. var instance = createInstance(services);
  171. instance.SetContext(context);
  172. try
  173. {
  174. instance.BeforeExecute(cmd);
  175. var task = method.Invoke(instance, args) as Task ?? Task.Delay(0);
  176. if (task is Task<RuntimeResult> resultTask)
  177. {
  178. return await resultTask.ConfigureAwait(false);
  179. }
  180. else
  181. {
  182. await task.ConfigureAwait(false);
  183. return ExecuteResult.FromSuccess();
  184. }
  185. }
  186. finally
  187. {
  188. instance.AfterExecute(cmd);
  189. (instance as IDisposable)?.Dispose();
  190. }
  191. }
  192. builder.Callback = ExecuteCallback;
  193. }
  194. private static void BuildParameter(ParameterBuilder builder, System.Reflection.ParameterInfo paramInfo, int position, int count, CommandService service)
  195. {
  196. var attributes = paramInfo.GetCustomAttributes();
  197. var paramType = paramInfo.ParameterType;
  198. builder.Name = paramInfo.Name;
  199. builder.IsOptional = paramInfo.IsOptional;
  200. builder.DefaultValue = paramInfo.HasDefaultValue ? paramInfo.DefaultValue : null;
  201. foreach (var attribute in attributes)
  202. {
  203. switch (attribute)
  204. {
  205. case SummaryAttribute summary:
  206. builder.Summary = summary.Text;
  207. break;
  208. case OverrideTypeReaderAttribute typeReader:
  209. builder.TypeReader = GetTypeReader(service, paramType, typeReader.TypeReader);
  210. break;
  211. case ParamArrayAttribute _:
  212. builder.IsMultiple = true;
  213. paramType = paramType.GetElementType();
  214. break;
  215. case ParameterPreconditionAttribute precon:
  216. builder.AddPrecondition(precon);
  217. break;
  218. case RemainderAttribute _:
  219. if (position != count - 1)
  220. throw new InvalidOperationException($"Remainder parameters must be the last parameter in a command. Parameter: {paramInfo.Name} in {paramInfo.Member.DeclaringType.Name}.{paramInfo.Member.Name}");
  221. builder.IsRemainder = true;
  222. break;
  223. default:
  224. builder.AddAttributes(attribute);
  225. break;
  226. }
  227. }
  228. builder.ParameterType = paramType;
  229. if (builder.TypeReader == null)
  230. {
  231. var readers = service.GetTypeReaders(paramType);
  232. TypeReader reader = null;
  233. if (readers != null)
  234. reader = readers.FirstOrDefault().Value;
  235. else
  236. reader = service.GetDefaultTypeReader(paramType);
  237. builder.TypeReader = reader;
  238. }
  239. }
  240. private static TypeReader GetTypeReader(CommandService service, Type paramType, Type typeReaderType)
  241. {
  242. var readers = service.GetTypeReaders(paramType);
  243. TypeReader reader = null;
  244. if (readers != null)
  245. {
  246. if (readers.TryGetValue(typeReaderType, out reader))
  247. return reader;
  248. }
  249. //We dont have a cached type reader, create one
  250. reader = ReflectionUtils.CreateObject<TypeReader>(typeReaderType.GetTypeInfo(), service, EmptyServiceProvider.Instance);
  251. service.AddTypeReader(paramType, reader);
  252. return reader;
  253. }
  254. private static bool IsValidModuleDefinition(TypeInfo typeInfo)
  255. {
  256. return _moduleTypeInfo.IsAssignableFrom(typeInfo) &&
  257. !typeInfo.IsAbstract;
  258. }
  259. private static bool IsValidCommandDefinition(MethodInfo methodInfo)
  260. {
  261. return methodInfo.IsDefined(typeof(CommandAttribute)) &&
  262. (methodInfo.ReturnType == typeof(Task) || methodInfo.ReturnType == typeof(Task<RuntimeResult>)) &&
  263. !methodInfo.IsStatic &&
  264. !methodInfo.IsGenericMethod;
  265. }
  266. }
  267. }