-
Notifications
You must be signed in to change notification settings - Fork 8
/
Rule.cs
321 lines (297 loc) · 11.2 KB
/
Rule.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Numerics;
using System.Reflection;
using System.Reflection.Metadata;
using System.Runtime.Loader;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using ExileCore;
using ExileCore.Shared.Enums;
using ExileCore.Shared.Nodes;
using ImGuiNET;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Scripting;
using Microsoft.CodeAnalysis.Scripting.Hosting;
using Newtonsoft.Json;
using ReAgent.SideEffects;
using ReAgent.State;
namespace ReAgent;
public class Rule
{
private static readonly Vector4 RuleTrueColor = new(0, 255, 0, 255);
private static readonly Vector4 RuleFalseColor = new(255, 255, 0, 255);
private static readonly Vector4 RulePendingColor = new(0, 255, 128, 255);
private static readonly Vector4 ExceptionColor = new(255, 0, 0, 255);
private static readonly ParsingConfig ParsingConfig = new ParsingConfig()
{ AllowNewToEvaluateAnyType = true, ResolveTypesBySimpleName = true, CustomTypeProvider = new CustomDynamicLinqCustomTypeProvider() };
static Rule()
{
unsafe
{
Assembly.GetExecutingAssembly().TryGetRawMetadata(out byte* blob, out int length);
var moduleMetadata = ModuleMetadata.CreateFromMetadata((IntPtr)blob, length);
var assemblyMetadata = AssemblyMetadata.Create(moduleMetadata);
metadataReference = assemblyMetadata.GetReference();
loader = new InteractiveAssemblyLoader();
loader.RegisterDependency(typeof(ReAgent).Assembly);
}
}
private ScriptOptions ScriptOptions => ScriptOptions.Default
.AddReferences(
typeof(Vector2).Assembly,
typeof(GameStat).Assembly,
typeof(Core).Assembly)
.AddReferences(metadataReference)
.AddImports(
"System.Collections.Generic", "System.Linq",
"ReAgent", "ReAgent.State",
"ExileCore", "ExileCore.Shared", "ExileCore.Shared.Enums",
"ExileCore.Shared.Helpers", "ExileCore.PoEMemory.Components", "ExileCore.PoEMemory.MemoryObjects",
"ExileCore.PoEMemory", "ExileCore.PoEMemory.FilesInMemory"
);
public string RuleSource;
public RuleActionType Type = RuleActionType.Key;
public Keys? Key = Keys.D0;
public int SyntaxVersion;
private Lazy<(Func<RuleState, IEnumerable<ISideEffect>> Func, string Exception)> _compilationResult;
private string _lastException;
private ulong _exceptionCounter;
private static readonly InteractiveAssemblyLoader loader;
private static readonly PortableExecutableReference metadataReference;
[JsonIgnore]
public int PendingEffectCount { get; set; }
public Rule(string ruleSource, int? syntaxVersion)
{
RuleSource = ruleSource;
SyntaxVersion = syntaxVersion ?? 1;
ResetFunction();
}
public void Display(RuleState state, bool expand)
{
if (expand)
{
if (ImguiExt.EnumerableComboBox("Action type", Enum.GetValues<RuleActionType>(), ref Type))
{
switch (Type)
{
case RuleActionType.Key:
Key = Keys.D0;
break;
case RuleActionType.SingleSideEffect:
case RuleActionType.MultipleSideEffects:
Key = null;
break;
}
ResetFunction();
}
}
else
{
ImGui.Text($"Action type: {Type}");
ImGui.SameLine();
}
if (Type == RuleActionType.Key)
{
var key = Key.Value;
if (expand)
{
var hotkeyNode = new HotkeyNode(key);
if (hotkeyNode.DrawPickerButton($"Key {key}"))
{
Key = hotkeyNode.Value;
}
}
else
{
ImGui.Text($"Presses key {key}");
ImGui.SameLine();
}
}
if (expand)
{
ImGui.TextWrapped("Rule source");
ImGui.SameLine();
var syntaxState = SyntaxVersion switch { 1 => false, 2 => true };
if (ImGui.Checkbox("Use new syntax", ref syntaxState))
{
SyntaxVersion = syntaxState ? 2 : 1;
ResetFunction();
}
if (ImGui.InputTextMultiline(
"##ruleSource",
ref RuleSource,
10000,
new Vector2(ImGui.GetContentRegionAvail().X, ImGui.CalcTextSize($"^{RuleSource}_").Y + ImGui.GetTextLineHeight())))
{
ResetFunction();
}
}
else
{
ImGui.TextUnformatted(Regex.Replace(RuleSource, "\\s+", " ") switch
{
{ Length: > 50 } s => $"{s[..50]}...",
var s => s
});
ImGui.SameLine();
}
var result = Evaluate(state);
if (_lastException != null)
{
ImGui.PushStyleColor(ImGuiCol.Text, ExceptionColor);
if (expand)
{
ImGui.TextWrapped(_lastException);
}
else
{
ImGui.TextUnformatted(_lastException);
}
ImGui.PopStyleColor();
}
else
{
var (color, text) = result switch
{
{ Count: > 0 } => (RuleTrueColor, $"Rule requests: [{string.Join(", ", result)}]."),
_ when PendingEffectCount > 0 => (RulePendingColor, $"Rule is waiting for {PendingEffectCount} side effects to apply"),
_ => (RuleFalseColor, "Rule is idle.")
};
if (_exceptionCounter > 0)
{
text += $" There were {_exceptionCounter} before";
}
ImGui.TextColored(color, text);
}
}
private void ResetFunction()
{
_exceptionCounter = 0;
_compilationResult = new(SyntaxVersion switch { 1 => RebuildFunctionV1, 2 => RebuildFunctionV2 }, LazyThreadSafetyMode.None);
}
private (Func<RuleState, IEnumerable<ISideEffect>> Func, string LastException) RebuildFunctionV1()
{
try
{
switch (Type)
{
case RuleActionType.Key:
{
var expression = DynamicExpressionParser.ParseLambda<RuleState, bool>(
ParsingConfig,
false,
RuleSource);
var boolFunc = expression.Compile();
return (s => boolFunc(s) ? [new PressKeySideEffect(Key ?? throw new Exception("Key is not assigned"))] : [], null);
}
case RuleActionType.SingleSideEffect:
{
var expression = DynamicExpressionParser.ParseLambda<RuleState, ISideEffect>(
ParsingConfig,
false,
RuleSource);
var effectFunc = expression.Compile();
return (s => effectFunc(s) switch { { } sideEffect => [sideEffect], _ => Enumerable.Empty<ISideEffect>() }, null);
}
case RuleActionType.MultipleSideEffects:
{
var expression = DynamicExpressionParser.ParseLambda<RuleState, IEnumerable<ISideEffect>>(
ParsingConfig,
false,
RuleSource);
var effectFunc = expression.Compile();
return (s => effectFunc(s) switch { { } sideEffects => sideEffects, _ => Enumerable.Empty<ISideEffect>() }, null);
}
default:
throw new Exception($"Invalid condition type: {Type}");
}
}
catch (Exception ex)
{
return (null, $"Expression compilation failed: {ex.Message}");
}
}
private delegate T ScriptFunc<T>(RuleState State);
private (Func<RuleState, IEnumerable<ISideEffect>> Func, string LastException) RebuildFunctionV2()
{
try
{
switch (Type)
{
case RuleActionType.Key:
{
var @delegate = DelegateCompiler.CompileDelegate<ScriptFunc<bool>>(RuleSource, ScriptOptions, CreateAlc());
return (s => @delegate(s)
? [new PressKeySideEffect(Key ?? throw new Exception("Key is not assigned"))]
: [], null);
}
case RuleActionType.SingleSideEffect:
{
var @delegate = DelegateCompiler.CompileDelegate<ScriptFunc<ISideEffect>>(RuleSource, ScriptOptions, CreateAlc());
return (s => @delegate(s) switch { { } sideEffect => [sideEffect], _ => Enumerable.Empty<ISideEffect>() },
null);
}
case RuleActionType.MultipleSideEffects:
{
var @delegate = DelegateCompiler.CompileDelegate<ScriptFunc<IEnumerable<ISideEffect>>>(RuleSource, ScriptOptions, CreateAlc());
return (s => @delegate(s) switch { { } sideEffects => sideEffects, _ => Enumerable.Empty<ISideEffect>() }, null);
}
default:
throw new Exception($"Invalid condition type: {Type}");
}
}
catch (Exception ex)
{
return (null, $"Expression compilation failed: {ex.Message}");
}
}
private static AssemblyLoadContext CreateAlc()
{
var assemblyLoadContext = new AssemblyLoadContext($"bbb{Guid.NewGuid()}", true);
assemblyLoadContext.Resolving += (context, name) => name.Name == "ReAgent" ? Assembly.GetExecutingAssembly() : null;
return assemblyLoadContext;
}
public IList<ISideEffect> Evaluate(RuleState state)
{
if (state == null) return [];
IList<ISideEffect> result = null;
var (func, compilationException) = _compilationResult.Value;
if (func != null)
{
if (PendingEffectCount == 0)
{
try
{
var intState = state.InternalState;
intState.AccessForbidden = true;
using (intState.CurrentGroupState.SetCurrentRule(this))
{
try
{
result = func(state).ToList();
_lastException = null;
}
finally
{
intState.AccessForbidden = false;
}
}
}
catch (Exception ex)
{
_lastException = $"Exception while evaluating ({_exceptionCounter}): {ex.Message}";
_exceptionCounter++;
}
}
}
else
{
_lastException = compilationException;
}
return result ?? new List<ISideEffect>();
}
}