-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCodeNode.cs
317 lines (265 loc) · 9.95 KB
/
CodeNode.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Reflection;
[JsonConverter(typeof(CodeNodeConverter))]
public abstract class CodeNode
{
internal const string OOPS_NAME = "oops!";
public virtual string NodeName { get; set; } = OOPS_NAME; // Unique name for addressing from parent
public virtual string Description { get; set; } = ""; // Notes about this node based on the language spec
public virtual string NodeValue { get; set; } = ""; // A ToString() view of the node.
const int START_END_NOT_SET = -1;
public int Start = START_END_NOT_SET;
public int End = START_END_NOT_SET; // exclusive range
internal AssemblyBytes Bytes { get; set; }
public List<CodeNode> Children = new List<CodeNode>();
public List<string> Errors = new List<string>();
public virtual CodeNode Link { get; set; } // MAYBE this should probably be protected, but need to figure out RVA
public string SelfPath { get; private set; }
string ecmaSection;
public virtual string EcmaSection {
get {
if (ecmaSection == null) {
GetType().TryGetAttribute(out EcmaAttribute e);
ecmaSection = e?.EcmaSection;
}
return ecmaSection;
}
set {
ecmaSection = value;
}
}
public void CallBack(Action<CodeNode> action) {
action(this);
foreach (var child in Children) {
child.CallBack(action);
}
}
public void AssignPath() => AssignPath(null);
void AssignPath(string parentPath) {
if (SelfPath != null)
throw new InvalidOperationException($"path was already {SelfPath}");
if (parentPath != null)
parentPath += "/";
SelfPath = parentPath + NodeName;
foreach (var c in Children) {
c.AssignPath(SelfPath);
}
}
public CodeNode Child(string name) {
return Children.Where(n => n.NodeName == name).Single();
}
public void Read() {
if (Bytes.PendingLink != null) {
if (Bytes.PendingLink.Link != null) throw new InvalidOperationException();
Bytes.PendingLink.Link = this;
Bytes.PendingLink = null;
}
Start = (int)Bytes.Stream.Position;
InnerRead();
if (End == START_END_NOT_SET) {
End = (int)Bytes.Stream.Position;
}
}
//TODO(PERF) skip reflection by having a source generator produce this exact code for each field
protected virtual void InnerRead() {
var orderedFields = this.GetType().GetFields()
.Where(field => field.DeclaringType != typeof(CodeNode))
.ToList();
if (orderedFields.Count > 1) {
orderedFields = orderedFields.OrderBy(field => {
if (field.TryGetAttribute(out OrderedFieldAttribute o)) return o.Order;
if (field.TryGetAttribute(out ExpectedAttribute e)) return e.Line;
if (field.TryGetAttribute(out DescriptionAttribute d)) return d.Line;
throw new InvalidOperationException($"{this.GetType().FullName}.{field.Name} is missing [OrderedField]");
}).ToList();
}
foreach (var field in orderedFields) {
AddChild(field.Name);
}
}
//TODO(PERF) add overloads i.e. CodeNode[] field to skip reflection? Use CallerArgumentExpression https://stackoverflow.com/a/70038692/771768
//TODO(PERF) Or, worth passing (x => Field3 = x) for a setter? OR, ref param?
protected void AddChild(string fieldName) {
var field = GetType().GetField(fieldName);
var type = field.FieldType;
field.TryGetAttribute(out EcmaAttribute ecma);
if (type.IsArray && type.GetElementType().IsSubclassOf(typeof(CodeNode))) {
var len = ((Array)field.GetValue(this))?.Length ?? GetCount(fieldName);
AddChildren(fieldName, len, ecma?.EcmaSection);
return;
}
var child = ReadField(fieldName);
Children.Add(child);
child.NodeName = fieldName;
if (field.TryGetAttribute(out DescriptionAttribute desc)) {
child.Description = (desc.Description + "\n" + child.Description).Trim();
}
if (ecma != null) {
child.EcmaSection = ecma.EcmaSection;
}
CheckExpected(field);
}
protected bool TryAddChild<T>(string fieldName, T expected) where T : struct {
if (expected.Equals(Bytes.Peek<T>())) {
AddChild(fieldName);
return true;
}
return false;
}
protected void ResizeLastChild() {
var child = Children.Last();
if (child.End == child.Start) {
Children.Remove(child);
}
if (child.Children.Count == 1) {
Children.Remove(child);
Children.Add(child.Children.Single());
}
}
protected void AddChildren(string fieldName, int length = -1, string ecmaSection = null) {
var field = GetType().GetField(fieldName);
var arr = (CodeNode[])(field.GetValue(this) ?? Activator.CreateInstance(field.FieldType, length));
field.SetValue(this, arr);
var elType = field.FieldType.GetElementType();
for (var i = 0; i < arr.Length; i++) {
var o = arr[i] ?? (CodeNode)Activator.CreateInstance(elType);
o.Bytes = Bytes;
o.Read();
arr[i] = o;
Children.Add(o);
o.NodeName = $"{fieldName}[{i}]";
if (ecmaSection != null) {
o.EcmaSection = ecmaSection;
}
}
CheckExpected(field);
}
protected virtual CodeNode ReadField(string fieldName) {
var field = GetType().GetField(fieldName);
var fieldType = field.FieldType;
if (fieldType.IsArray) {
var elementType = fieldType.GetElementType();
if (elementType.IsValueType) {
int len;
if (field.TryGetAttribute(out ExpectedAttribute e)) {
if (e.Value is string s) {
len = s.Length;
} else {
len = ((Array)e.Value).Length;
}
} else {
len = GetCount(fieldName);
}
var san = typeof(StructArrayNode<>).MakeGenericType(elementType);
var o = (CodeNode)Activator.CreateInstance(san, len);
o.Bytes = Bytes;
o.Read();
var value = san.GetField("arr").GetValue(o);
field.SetValue(this, value);
o.NodeValue = value.GetString();
return o;
}
throw new InvalidOperationException($"{GetType().FullName}. {field.Name} is an array {elementType}[]");
}
if (fieldType.IsClass) {
var o = (CodeNode)(field.GetValue(this) ?? (CodeNode)Activator.CreateInstance(fieldType));
o.Bytes = Bytes;
o.Read();
field.SetValue(this, o);
return o;
}
Type sn;
if (fieldType.IsEnum) {
sn = typeof(EnumNode<>).MakeGenericType(fieldType); ;
} else if (fieldType.IsValueType) {
sn = typeof(StructNode<>).MakeGenericType(fieldType);
} else {
throw new InvalidOperationException(fieldType.Name);
}
{
CodeNode o = (CodeNode)Activator.CreateInstance(sn);
o.Bytes = Bytes;
o.Read();
var value = sn.GetField("t").GetValue(o);
field.SetValue(this, value);
o.NodeValue = value.GetString();
return o;
}
}
protected virtual int GetCount(string field) =>
throw new InvalidOperationException($"{GetType().Name} .{field}");
void CheckExpected(FieldInfo field) {
if (field.TryGetAttribute(out ExpectedAttribute expected)) {
var actual = field.GetValue(this);
if (!TypeExtensions.SmartEquals(expected.Value, actual)) {
Errors.Add($"Expected {field.Name} to be {expected.Value.GetString()} but instead found {actual.GetString()} at address 0x{Start:X}");
}
}
}
public string ToJson(JsonSerializerOptions options = null) {
if (options is null) {
options = new JsonSerializerOptions();
} else {
options = new JsonSerializerOptions(options);
}
options.MaxDepth = 256;
return JsonSerializer.Serialize(this, options);
}
sealed class CodeNodeConverter : JsonConverter<CodeNode>
{
public override CodeNode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => throw new NotImplementedException();
public override void Write(Utf8JsonWriter writer, CodeNode node, JsonSerializerOptions options) {
writer.WriteStartObject();
writer.WriteString("Name", node.NodeName);
writer.WriteString(nameof(node.Description), node.Description);
writer.WriteString("Value", node.NodeValue);
writer.WriteNumber(nameof(node.Start), node.Start);
writer.WriteNumber(nameof(node.End), node.End);
writer.WriteString("LinkPath", node.Link?.SelfPath);
writer.WriteString("Ecma", node.EcmaSection);
writer.WritePropertyName(nameof(node.Errors));
JsonSerializer.Serialize(writer, node.Errors);
writer.WritePropertyName(nameof(node.Children));
JsonSerializer.Serialize(writer, node.Children);
writer.WriteEndObject();
}
}
}
public sealed class StructArrayNode<T> : CodeNode where T : struct
{
public T[] arr;
public int Length { get; }
public StructArrayNode(int length) {
Length = length;
}
protected override void InnerRead() {
arr = Enumerable.Range(0, Length).Select(_ => {
var node = new StructNode<T> { Bytes = Bytes };
node.Read();
return node.t;
}).ToArray();
}
}
public sealed class StructNode<T> : CodeNode where T : struct
{
public T t;
protected override void InnerRead() {
t = Bytes.Read<T>();
NodeValue = t.GetString();
}
}
public sealed class EnumNode<T> : CodeNode where T : struct, Enum
{
public T t;
public override string EcmaSection => base.EcmaSection ?? (typeof(T).TryGetAttribute(out EcmaAttribute e) ? e.EcmaSection : null);
protected override void InnerRead() {
t = Bytes.Read<T>();
NodeValue = t.GetString();
Description = string.Join('\n', t.Describe());
}
//TODO(fixme) think about this pattern: DON'T override Description because CodeNode expects to use the setter if the enum fieldinfo also has a description
}