Skip to content

Commit

Permalink
more cleanup & speed up PatchCategory(...)
Browse files Browse the repository at this point in the history
  • Loading branch information
pardeike committed Feb 12, 2024
1 parent 3422ff5 commit 3869952
Show file tree
Hide file tree
Showing 22 changed files with 79 additions and 94 deletions.
12 changes: 6 additions & 6 deletions Harmony/Internal/CodeTranspiler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ internal static bool ShouldAddExceptionInfo(object op, int opIndex, List<object>
if (unassigned.TryGetValue(nameof(CodeInstruction.blocks), out blocksObject) is false)
return false;
blocks = blocksObject as List<ExceptionBlock>;
return blocks.Any();
return blocks.Count > 0;
});
if (pairInstruction is not null)
{
Expand All @@ -92,15 +92,15 @@ internal static bool ShouldAddExceptionInfo(object op, int opIndex, List<object>
if (unassigned.TryGetValue(nameof(CodeInstruction.blocks), out blocksObject) is false)
return false;
blocks = blocksObject as List<ExceptionBlock>;
return blocks.Any();
return blocks.Count > 0;
});
if (pairInstruction is not null)
{
pairStart = opIndex + 1;
pairEnd = pairStart + newInstructions.Skip(opIndex + 1).ToList().IndexOf(pairInstruction) - 1;
var newBetweenInstructions = newInstructions.GetRange(pairStart, pairEnd - pairStart);
var remaining = originalBetweenInstructions.Except(newBetweenInstructions).ToList();
return remaining.Any() is false;
return remaining.Count == 0;
}
}
}
Expand All @@ -113,7 +113,7 @@ internal static bool ShouldAddExceptionInfo(object op, int opIndex, List<object>
if (unassigned.TryGetValue(nameof(CodeInstruction.blocks), out blocksObject) is false)
return false;
blocks = blocksObject as List<ExceptionBlock>;
return blocks.Any();
return blocks.Count > 0;
});
if (pairInstruction is not null)
{
Expand All @@ -130,7 +130,7 @@ internal static bool ShouldAddExceptionInfo(object op, int opIndex, List<object>
if (unassigned.TryGetValue(nameof(CodeInstruction.blocks), out blocksObject) is false)
return false;
blocks = blocksObject as List<ExceptionBlock>;
return blocks.Any();
return blocks.Count > 0;
});
if (pairInstruction is not null)
{
Expand Down Expand Up @@ -240,7 +240,7 @@ internal List<CodeInstruction> GetResult(ILGenerator generator, MethodBase metho

// call the transpiler
var parameter = GetTranspilerCallParameters(generator, transpiler, method, instructions);
var newInstructions = transpiler.Invoke(null, parameter.ToArray()) as IEnumerable;
var newInstructions = transpiler.Invoke(null, [.. parameter]) as IEnumerable;
if (newInstructions is object)
instructions = newInstructions;

Expand Down
2 changes: 1 addition & 1 deletion Harmony/Internal/InlineSignatureParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ object ReadTypeSignature()
throw new NotSupportedException($"Unsupported generic callsite element: {etype}");

case MetadataType.GenericInstance:
reader.ReadByte(); // element type, unused
_ = reader.ReadByte(); // element type, unused
var elType = GetTypeDefOrRef();
var arity = (int)ReadCompressedUInt32();

Expand Down
2 changes: 1 addition & 1 deletion Harmony/Internal/MethodCopier.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ internal static List<CodeInstruction> GetInstructions(ILGenerator generator, Met
var info = Harmony.GetPatchInfo(method);
if (info is not null)
{
var sortedTranspilers = PatchFunctions.GetSortedPatchMethods(method, info.Transpilers.ToArray(), false);
var sortedTranspilers = PatchFunctions.GetSortedPatchMethods(method, [.. info.Transpilers], false);
for (var i = 0; i < maxTranspilers && i < sortedTranspilers.Count; i++)
copier.AddTranspiler(sortedTranspilers[i]);
}
Expand Down
6 changes: 3 additions & 3 deletions Harmony/Internal/MethodPatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ internal MethodInfo CreateReplacement(out Dictionary<int, CodeInstruction> final
});

LocalBuilder finalizedVariable = null;
if (finalizers.Any())
if (finalizers.Count > 0)
{
finalizedVariable = DeclareLocalVariable(typeof(bool));

Expand Down Expand Up @@ -155,7 +155,7 @@ internal MethodInfo CreateReplacement(out Dictionary<int, CodeInstruction> final

var needsToStorePassthroughResult = AddPostfixes(privateVars, runOriginalVariable, true);

var hasFinalizers = finalizers.Any();
var hasFinalizers = finalizers.Count > 0;
if (hasFinalizers)
{
if (needsToStorePassthroughResult)
Expand Down Expand Up @@ -244,7 +244,7 @@ internal static DynamicMethodDefinition CreateDynamicMethod(MethodBase original,
var method = new DynamicMethodDefinition(
patchName,
returnType,
parameterTypes.ToArray()
[.. parameterTypes]
)
{
// OwnerType = original.DeclaringType
Expand Down
2 changes: 1 addition & 1 deletion Harmony/Internal/PatchFunctions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ internal static MethodInfo ReversePatch(HarmonyMethod standin, MethodBase origin
if (standin.reversePatchType == HarmonyReversePatchType.Snapshot)
{
var info = Harmony.GetPatchInfo(original);
transpilers.AddRange(GetSortedPatchMethods(original, info.Transpilers.ToArray(), debug));
transpilers.AddRange(GetSortedPatchMethods(original, [.. info.Transpilers], debug));
}
if (postTranspiler is not null) transpilers.Add(postTranspiler);

Expand Down
1 change: 0 additions & 1 deletion Harmony/Internal/PatchTools.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ internal static class PatchTools
private static readonly Dictionary<MethodBase, ICoreDetour> detours = [];
internal static readonly string harmonyMethodFullName = typeof(HarmonyMethod).FullName;
internal static readonly string harmonyAttributeFullName = typeof(HarmonyAttribute).FullName;
internal static readonly string harmonyPatchCategoryFullName = typeof(HarmonyPatchCategory).FullName;
internal static readonly string harmonyPatchAllFullName = typeof(HarmonyPatchAll).FullName;

internal static void DetourMethod(MethodBase method, MethodBase replacement)
Expand Down
2 changes: 1 addition & 1 deletion Harmony/Public/Attributes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,7 @@ void ParseSpecialArguments(Type[] argumentTypes, ArgumentType[] argumentVariatio
}
types.Add(type);
}
info.argumentTypes = types.ToArray();
info.argumentTypes = [.. types];
}
}

Expand Down
6 changes: 3 additions & 3 deletions Harmony/Public/CodeInstruction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ public CodeInstruction(CodeInstruction instruction)
{
opcode = instruction.opcode;
operand = instruction.operand;
labels = instruction.labels.ToList();
blocks = instruction.blocks.ToList();
labels = [.. instruction.labels];
blocks = [.. instruction.blocks];
}

// --- CLONING
Expand Down Expand Up @@ -316,7 +316,7 @@ public override string ToString()
foreach (var block in blocks)
list.Add($"EX_{block.blockType.ToString().Replace("Block", "")}");

var extras = list.Count > 0 ? $" [{string.Join(", ", list.ToArray())}]" : "";
var extras = list.Count > 0 ? $" [{string.Join(", ", [.. list])}]" : "";
var operandStr = Emitter.FormatArgument(operand);
if (operandStr.Length > 0) operandStr = " " + operandStr;
return opcode + operandStr + extras;
Expand Down
20 changes: 7 additions & 13 deletions Harmony/Public/ExceptionBlock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,24 +33,18 @@ public enum ExceptionBlockType

/// <summary>An exception block</summary>
///
public class ExceptionBlock
/// <remarks>Creates an exception block</remarks>
/// <param name="blockType">The <see cref="ExceptionBlockType"/></param>
/// <param name="catchType">The catch type</param>
///
public class ExceptionBlock(ExceptionBlockType blockType, Type catchType = null)
{
/// <summary>Block type</summary>
///
public ExceptionBlockType blockType;
public ExceptionBlockType blockType = blockType;

/// <summary>Catch type</summary>
///
public Type catchType;

/// <summary>Creates an exception block</summary>
/// <param name="blockType">The <see cref="ExceptionBlockType"/></param>
/// <param name="catchType">The catch type</param>
///
public ExceptionBlock(ExceptionBlockType blockType, Type catchType = null)
{
this.blockType = blockType;
this.catchType = catchType ?? typeof(object);
}
public Type catchType = catchType ?? typeof(object);
}
}
11 changes: 7 additions & 4 deletions Harmony/Public/Harmony.cs
Original file line number Diff line number Diff line change
Expand Up @@ -153,10 +153,13 @@ public void PatchCategory(string category)
public void PatchCategory(Assembly assembly, string category)
{
AccessTools.GetTypesFromAssembly(assembly)
.Where(type => type.GetCustomAttributes(true).Any(a => a.GetType().FullName == PatchTools.harmonyPatchCategoryFullName))
.Select(CreateClassProcessor)
.Where(patchClass => patchClass.Category == category)
.Do(patchClass => patchClass.Patch());
.Where(type =>
{
var harmonyAttributes = HarmonyMethodExtensions.GetFromType(type);
var containerAttributes = HarmonyMethod.Merge(harmonyAttributes);
return containerAttributes.category == category;
})
.Do(type => CreateClassProcessor(type).Patch());
}

/// <summary>Creates patches by manually specifying the methods</summary>
Expand Down
2 changes: 1 addition & 1 deletion Harmony/Public/HarmonyException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ internal static Exception Create(Exception ex, Dictionary<int, CodeInstruction>
///
public List<KeyValuePair<int, CodeInstruction>> GetInstructionsWithOffsets()
{
return instructions.OrderBy(ins => ins.Key).ToList();
return [.. instructions.OrderBy(ins => ins.Key)];
}

/// <summary>Get a list of IL instructions without offsets</summary>
Expand Down
2 changes: 1 addition & 1 deletion Harmony/Public/HarmonyMethod.cs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ public static List<string> HarmonyFields()
public static HarmonyMethod Merge(List<HarmonyMethod> attributes)
{
var result = new HarmonyMethod();
if (attributes is null) return result;
if (attributes is null || attributes.Count == 0) return result;
var resultTrv = Traverse.Create(result);
attributes.ForEach(attribute =>
{
Expand Down
20 changes: 11 additions & 9 deletions Harmony/Public/Patch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ namespace HarmonyLib
internal static class PatchInfoSerialization
{
#if NET5_0_OR_GREATER
static readonly JsonSerializerOptions serializerOptions = new() { IncludeFields = true };
internal static bool? useBinaryFormatter = null;
internal static bool UseBinaryFormatter
{
Expand Down Expand Up @@ -98,8 +99,7 @@ internal static PatchInfo Deserialize(byte[] bytes)
}
else
{
var options = new JsonSerializerOptions { IncludeFields = true };
return JsonSerializer.Deserialize<PatchInfo>(bytes, options);
return JsonSerializer.Deserialize<PatchInfo>(bytes, serializerOptions);
}
#endif
}
Expand Down Expand Up @@ -283,13 +283,15 @@ private static Patch[] Add(string owner, HarmonyMethod[] add, Patch[] current)

// concat lists
var initialIndex = current.Length;
return current
.Concat(
add
.Where(method => method != null)
.Select((method, i) => new Patch(method, i + initialIndex, owner))
)
.ToArray();
return
[
.. current
,
.. add
.Where(method => method != null)
.Select((method, i) => new Patch(method, i + initialIndex, owner))
,
];
}

/// <summary>Gets a list of patches with any from the given owner removed</summary>
Expand Down
8 changes: 4 additions & 4 deletions Harmony/Public/PatchClassProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -187,10 +187,10 @@ void ProcessPatchJob(PatchJobs<MethodInfo>.Job job)
{
var patchInfo = HarmonySharedState.GetPatchInfo(job.original) ?? new PatchInfo();

patchInfo.AddPrefixes(instance.Id, job.prefixes.ToArray());
patchInfo.AddPostfixes(instance.Id, job.postfixes.ToArray());
patchInfo.AddTranspilers(instance.Id, job.transpilers.ToArray());
patchInfo.AddFinalizers(instance.Id, job.finalizers.ToArray());
patchInfo.AddPrefixes(instance.Id, [.. job.prefixes]);
patchInfo.AddPostfixes(instance.Id, [.. job.postfixes]);
patchInfo.AddTranspilers(instance.Id, [.. job.transpilers]);
patchInfo.AddFinalizers(instance.Id, [.. job.finalizers]);

replacement = PatchFunctions.UpdateWrapper(job.original, patchInfo);
HarmonySharedState.UpdatePatchInfo(job.original, replacement, patchInfo);
Expand Down
2 changes: 1 addition & 1 deletion Harmony/Public/PatchJsonConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public override Patch Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSe
// we shall not read end object here
//_ = reader.Read();

return new Patch(index, owner, priority, before.ToArray(), after.ToArray(), debug, methodToken, moduleGUID);
return new Patch(index, owner, priority, [.. before], [.. after], debug, methodToken, moduleGUID);
}

public override void Write(Utf8JsonWriter writer, Patch patchValue, JsonSerializerOptions options)
Expand Down
22 changes: 8 additions & 14 deletions Harmony/Public/PatchProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,14 @@ namespace HarmonyLib
{
/// <summary>A PatchProcessor handles patches on a method/constructor</summary>
///
public class PatchProcessor
/// <remarks>Creates an empty patch processor</remarks>
/// <param name="instance">The Harmony instance</param>
/// <param name="original">The original method/constructor</param>
///
public class PatchProcessor(Harmony instance, MethodBase original)
{
readonly Harmony instance;
readonly MethodBase original;
readonly Harmony instance = instance;
readonly MethodBase original = original;

HarmonyMethod prefix;
HarmonyMethod postfix;
Expand All @@ -21,16 +25,6 @@ public class PatchProcessor

internal static readonly object locker = new();

/// <summary>Creates an empty patch processor</summary>
/// <param name="instance">The Harmony instance</param>
/// <param name="original">The original method/constructor</param>
///
public PatchProcessor(Harmony instance, MethodBase original)
{
this.instance = instance;
this.original = original;
}

/// <summary>Adds a prefix</summary>
/// <param name="prefix">The prefix as a <see cref="HarmonyMethod"/></param>
/// <returns>A <see cref="PatchProcessor"/> for chaining calls</returns>
Expand Down Expand Up @@ -266,7 +260,7 @@ public static ILGenerator CreateILGenerator(MethodBase original)
var returnType = original is MethodInfo m ? m.ReturnType : typeof(void);
var parameterTypes = original.GetParameters().Select(pi => pi.ParameterType).ToList();
if (original.IsStatic is false) parameterTypes.Insert(0, original.DeclaringType);
var method = new DynamicMethodDefinition($"ILGenerator_{original.Name}", returnType, parameterTypes.ToArray());
var method = new DynamicMethodDefinition($"ILGenerator_{original.Name}", returnType, [.. parameterTypes]);
return method.GetILGenerator();
}

Expand Down
25 changes: 9 additions & 16 deletions Harmony/Public/ReversePatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,16 @@ namespace HarmonyLib
{
/// <summary>A reverse patcher</summary>
///
public class ReversePatcher
/// <remarks>Creates a reverse patcher</remarks>
/// <param name="instance">The Harmony instance</param>
/// <param name="original">The original method/constructor</param>
/// <param name="standin">Your stand-in stub method as <see cref="HarmonyMethod"/></param>
///
public class ReversePatcher(Harmony instance, MethodBase original, HarmonyMethod standin)
{
readonly Harmony instance;
readonly MethodBase original;
readonly HarmonyMethod standin;

/// <summary>Creates a reverse patcher</summary>
/// <param name="instance">The Harmony instance</param>
/// <param name="original">The original method/constructor</param>
/// <param name="standin">Your stand-in stub method as <see cref="HarmonyMethod"/></param>
///
public ReversePatcher(Harmony instance, MethodBase original, HarmonyMethod standin)
{
this.instance = instance;
this.original = original;
this.standin = standin;
}
readonly Harmony instance = instance;
readonly MethodBase original = original;
readonly HarmonyMethod standin = standin;

/// <summary>Applies the patch</summary>
/// <param name="type">The type of patch, see <see cref="HarmonyReversePatchType"/></param>
Expand Down
Loading

0 comments on commit 3869952

Please sign in to comment.