-
Notifications
You must be signed in to change notification settings - Fork 0
/
CecilExtension.cs
64 lines (57 loc) · 2.15 KB
/
CecilExtension.cs
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
using Mono.Cecil;
using Mono.Cecil.Cil;
using System;
using System.Collections.Generic;
using System.Linq;
namespace TuPack
{
static class CecilExtension
{
public static void Insert(this MethodBody body, int index, IEnumerable<Instruction> instructions)
{
instructions = instructions.Reverse();
foreach (var instruction in instructions)
{
body.Instructions.Insert(index, instruction);
}
}
public static bool IsLeaveInstruction(this Instruction instruction)
{
return instruction.OpCode == OpCodes.Leave || instruction.OpCode == OpCodes.Leave_S;
}
public static bool IsInstanceConstructor(this MethodDefinition methodDefinition)
{
return methodDefinition.IsConstructor && !methodDefinition.IsStatic;
}
public static CustomAttribute GetAsyncStateMachineAttribute(this MethodDefinition method)
{
return method.CustomAttributes.FirstOrDefault(_ => _.AttributeType.Name == "AsyncStateMachineAttribute");
}
public static bool IsAsync(this MethodDefinition method)
{
return GetAsyncStateMachineAttribute(method) != null;
}
public static bool IsYield(this MethodDefinition method)
{
if (method.ReturnType is null)
{
return false;
}
if (!method.ReturnType.Name.StartsWith("IEnumerable"))
{
return false;
}
var stateMachinePrefix = $"<{method.Name}>";
var nestedTypes = method.DeclaringType.NestedTypes;
return nestedTypes.Any(x => x.Name.StartsWith(stateMachinePrefix));
}
public static IEnumerable<MethodDefinition> ConcreteMethods(this TypeDefinition type)
{
return type.Methods.Where(x => !x.IsAbstract && x.HasBody && !IsEmptyConstructor(x));
}
static bool IsEmptyConstructor(this MethodDefinition method)
{
return method.Name == ".ctor" && method.Body.Instructions.Count(x => x.OpCode != OpCodes.Nop) == 3;
}
}
}