Resolvers.cs 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 scriptDef, string name)
  13. {
  14. if (tr == null)
  15. {
  16. Weaver.Error($"Cannot resolve method {name} without a class");
  17. return null;
  18. }
  19. MethodReference method = ResolveMethod(tr, scriptDef, m => m.Name == name);
  20. if (method == null)
  21. {
  22. Weaver.Error($"Method not found with name {name} in type {tr.Name}", tr);
  23. }
  24. return method;
  25. }
  26. public static MethodReference ResolveMethod(TypeReference t, AssemblyDefinition scriptDef, System.Func<MethodDefinition, bool> predicate)
  27. {
  28. foreach (MethodDefinition methodRef in t.Resolve().Methods)
  29. {
  30. if (predicate(methodRef))
  31. {
  32. return scriptDef.MainModule.ImportReference(methodRef);
  33. }
  34. }
  35. Weaver.Error($"Method not found in type {t.Name}", t);
  36. return null;
  37. }
  38. public static MethodReference TryResolveMethodInParents(TypeReference tr, AssemblyDefinition scriptDef, string name)
  39. {
  40. if (tr == null)
  41. {
  42. return null;
  43. }
  44. foreach (MethodDefinition methodRef in tr.Resolve().Methods)
  45. {
  46. if (methodRef.Name == name)
  47. {
  48. return scriptDef.MainModule.ImportReference(methodRef);
  49. }
  50. }
  51. // Could not find the method in this class, try the parent
  52. return TryResolveMethodInParents(tr.Resolve().BaseType, scriptDef, name);
  53. }
  54. public static MethodDefinition ResolveDefaultPublicCtor(TypeReference variable)
  55. {
  56. foreach (MethodDefinition methodRef in variable.Resolve().Methods)
  57. {
  58. if (methodRef.Name == ".ctor" &&
  59. methodRef.Resolve().IsPublic &&
  60. methodRef.Parameters.Count == 0)
  61. {
  62. return methodRef;
  63. }
  64. }
  65. return null;
  66. }
  67. public static MethodReference ResolveProperty(TypeReference tr, AssemblyDefinition scriptDef, string name)
  68. {
  69. foreach (PropertyDefinition pd in tr.Resolve().Properties)
  70. {
  71. if (pd.Name == name)
  72. {
  73. return scriptDef.MainModule.ImportReference(pd.GetMethod);
  74. }
  75. }
  76. return null;
  77. }
  78. }
  79. }