Resolvers.cs 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // all the resolve functions for the weaver
  2. // NOTE: these functions should be made extensions, but right now they still
  3. // make heavy use of Weaver.fail and we'd have to check each one's return
  4. // value for null otherwise.
  5. // (original FieldType.Resolve returns null if not found too, so
  6. // exceptions would be a bit inconsistent here)
  7. using Mono.CecilX;
  8. namespace Mirror.Weaver
  9. {
  10. public static class Resolvers
  11. {
  12. public static MethodReference ResolveMethod(TypeReference tr, AssemblyDefinition assembly, Logger Log, string name, ref bool WeavingFailed)
  13. {
  14. if (tr == null)
  15. {
  16. Log.Error($"Cannot resolve method {name} without a class");
  17. WeavingFailed = true;
  18. return null;
  19. }
  20. MethodReference method = ResolveMethod(tr, assembly, Log, m => m.Name == name, ref WeavingFailed);
  21. if (method == null)
  22. {
  23. Log.Error($"Method not found with name {name} in type {tr.Name}", tr);
  24. WeavingFailed = true;
  25. }
  26. return method;
  27. }
  28. public static MethodReference ResolveMethod(TypeReference t, AssemblyDefinition assembly, Logger Log, System.Func<MethodDefinition, bool> predicate, ref bool WeavingFailed)
  29. {
  30. foreach (MethodDefinition methodRef in t.Resolve().Methods)
  31. {
  32. if (predicate(methodRef))
  33. {
  34. return assembly.MainModule.ImportReference(methodRef);
  35. }
  36. }
  37. Log.Error($"Method not found in type {t.Name}", t);
  38. WeavingFailed = true;
  39. return null;
  40. }
  41. public static MethodReference TryResolveMethodInParents(TypeReference tr, AssemblyDefinition assembly, string name)
  42. {
  43. if (tr == null)
  44. {
  45. return null;
  46. }
  47. foreach (MethodDefinition methodRef in tr.Resolve().Methods)
  48. {
  49. if (methodRef.Name == name)
  50. {
  51. return assembly.MainModule.ImportReference(methodRef);
  52. }
  53. }
  54. // Could not find the method in this class, try the parent
  55. return TryResolveMethodInParents(tr.Resolve().BaseType, assembly, name);
  56. }
  57. public static MethodDefinition ResolveDefaultPublicCtor(TypeReference variable)
  58. {
  59. foreach (MethodDefinition methodRef in variable.Resolve().Methods)
  60. {
  61. if (methodRef.Name == ".ctor" &&
  62. methodRef.Resolve().IsPublic &&
  63. methodRef.Parameters.Count == 0)
  64. {
  65. return methodRef;
  66. }
  67. }
  68. return null;
  69. }
  70. public static MethodReference ResolveProperty(TypeReference tr, AssemblyDefinition assembly, string name)
  71. {
  72. foreach (PropertyDefinition pd in tr.Resolve().Properties)
  73. {
  74. if (pd.Name == name)
  75. {
  76. return assembly.MainModule.ImportReference(pd.GetMethod);
  77. }
  78. }
  79. return null;
  80. }
  81. }
  82. }