-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogic.js
More file actions
845 lines (750 loc) · 28.1 KB
/
logic.js
File metadata and controls
845 lines (750 loc) · 28.1 KB
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
const ReqType = Object.freeze({
MEM: { name: "Mem", prefix: "", addr: true, cprio: 10, },
DELTA: { name: "Delta", prefix: "d", addr: true, cprio: 11, },
PRIOR: { name: "Prior", prefix: "p", addr: true, cprio: 11, },
BCD: { name: "BCD", prefix: "b", addr: true, cprio: 12, },
INVERT: { name: "Invert", prefix: "~", addr: true, cprio: 12, },
RECALL: { name: "Recall", prefix: "{recall}", addr: false, cprio: 20, },
VALUE: { name: "Value", prefix: "v", addr: false, cprio: 21, },
FLOAT: { name: "Float", prefix: "f", addr: false, cprio: 21, },
});
/*
@property name: flag name
@property prefix: rcheevos syntax logic prefix
@property chain: (boolean) does the flag connect this requirement to the next one?
@property scalable: (boolean) can this requirement have a source modification?
@property cmod: (boolean) is this a combining modifier flag?
*/
const ReqFlag = Object.freeze({
PAUSEIF: { name: "PauseIf", prefix: "P:", chain: false, scalable: false, cmod: false, },
RESETIF: { name: "ResetIf", prefix: "R:", chain: false, scalable: false, cmod: false, },
RESETNEXTIF: { name: "ResetNextIf", prefix: "Z:", chain: true, scalable: false, cmod: false, },
ADDSOURCE: { name: "AddSource", prefix: "A:", chain: true, scalable: true , cmod: true , },
SUBSOURCE: { name: "SubSource", prefix: "B:", chain: true, scalable: true , cmod: true , },
ADDHITS: { name: "AddHits", prefix: "C:", chain: true, scalable: false, cmod: false, },
SUBHITS: { name: "SubHits", prefix: "D:", chain: true, scalable: false, cmod: false, },
ADDADDRESS: { name: "AddAddress", prefix: "I:", chain: true, scalable: true , cmod: true , },
ANDNEXT: { name: "AndNext", prefix: "N:", chain: true, scalable: false, cmod: true , },
ORNEXT: { name: "OrNext", prefix: "O:", chain: true, scalable: false, cmod: true , },
MEASURED: { name: "Measured", prefix: "M:", chain: false, scalable: false, cmod: false, },
MEASUREDP: { name: "Measured%", prefix: "G:", chain: false, scalable: false, cmod: false, },
MEASUREDIF: { name: "MeasuredIf", prefix: "Q:", chain: false, scalable: false, cmod: false, },
TRIGGER: { name: "Trigger", prefix: "T:", chain: false, scalable: false, cmod: false, },
REMEMBER: { name: "Remember", prefix: "K:", chain: false, scalable: true , cmod: false, },
});
const MemSize = Object.freeze({
BYTE: { name: "8-bit", prefix: "0xH", bytes: 1, maxvalue: 0xFF, },
WORD: { name: "16-bit", prefix: "0x", bytes: 2, maxvalue: 0xFFFF, },
TBYTE: { name: "24-bit", prefix: "0xW", bytes: 3, maxvalue: 0xFFFFFF, },
DWORD: { name: "32-bit", prefix: "0xX", bytes: 4, maxvalue: 0xFFFFFFFF, },
WORD_BE: { name: "16-bit BE", prefix: "0xI", bytes: 2, maxvalue: 0xFFFF, },
TBYTE_BE: { name: "24-bit BE", prefix: "0xJ", bytes: 3, maxvalue: 0xFFFFFF, },
DWORD_BE: { name: "32-bit BE", prefix: "0xG", bytes: 4, maxvalue: 0xFFFFFFFF, },
LOWER4: { name: "Lower4", prefix: "0xL", bytes: 1, maxvalue: 0xF, },
UPPER4: { name: "Upper4", prefix: "0xU", bytes: 1, maxvalue: 0xF, },
FLOAT: { name: "Float", prefix: "fF", bytes: 4, maxvalue: Number.POSITIVE_INFINITY, },
FLOAT_BE: { name: "Float BE", prefix: "fB", bytes: 4, maxvalue: Number.POSITIVE_INFINITY, },
DBL32: { name: "Double32", prefix: "fH", bytes: 8, maxvalue: Number.POSITIVE_INFINITY, },
DBL32_BE: { name: "Double32 BE", prefix: "fI", bytes: 8, maxvalue: Number.POSITIVE_INFINITY, },
MBF32: { name: "MBF32", prefix: "fM", bytes: 4, maxvalue: Number.POSITIVE_INFINITY, },
MBF32_LE: { name: "MBF32 LE", prefix: "fL", bytes: 4, maxvalue: Number.POSITIVE_INFINITY, },
BIT0: { name: "Bit0", prefix: "0xM", bytes: 1, maxvalue: 1, },
BIT1: { name: "Bit1", prefix: "0xN", bytes: 1, maxvalue: 1, },
BIT2: { name: "Bit2", prefix: "0xO", bytes: 1, maxvalue: 1, },
BIT3: { name: "Bit3", prefix: "0xP", bytes: 1, maxvalue: 1, },
BIT4: { name: "Bit4", prefix: "0xQ", bytes: 1, maxvalue: 1, },
BIT5: { name: "Bit5", prefix: "0xR", bytes: 1, maxvalue: 1, },
BIT6: { name: "Bit6", prefix: "0xS", bytes: 1, maxvalue: 1, },
BIT7: { name: "Bit7", prefix: "0xT", bytes: 1, maxvalue: 1, },
BITCOUNT: { name: "BitCount", prefix: "0xK", bytes: 1, maxvalue: 8, },
});
const FormatType = Object.freeze({
POINTS: { name: "Score", type: "POINTS", category: "value", },
SCORE: { name: "Score", type: "SCORE", category: "value", },
FRAMES: { name: "Frames", type: "FRAMES", category: "time", },
TIME: { name: "Frames", type: "TIME", category: "time", },
MILLISECS: { name: "Centiseconds", type: "MILLISECS", category: "time", },
TIMESECS: { name: "Seconds", type: "TIMESECS", category: "time", },
SECS: { name: "Seconds", type: "SECS", category: "time", },
MINUTES: { name: "Minutes", type: "MINUTES", category: "time", },
SECS_AS_MINS: { name: "Seconds", type: "SECS_AS_MINS", category: "time", },
VALUE: { name: "Value", type: "VALUE", category: "value", },
UNSIGNED: { name: "Unsigned", type: "UNSIGNED", category: "value", },
TENS: { name: "Value × 10", type: "TENS", category: "value", },
HUNDREDS: { name: "Value × 100", type: "HUNDREDS", category: "value", },
THOUSANDS: { name: "Value × 1000", type: "THOUSANDS", category: "value", },
FIXED1: { name: "Fixed1", type: "FIXED1", category: "value", },
FIXED2: { name: "Fixed2", type: "FIXED2", category: "value", },
FIXED3: { name: "Fixed3", type: "FIXED3", category: "value", },
FLOAT1: { name: "Float1", type: "FLOAT1", category: "value", },
FLOAT2: { name: "Float2", type: "FLOAT2", category: "value", },
FLOAT3: { name: "Float3", type: "FLOAT3", category: "value", },
FLOAT4: { name: "Float4", type: "FLOAT4", category: "value", },
FLOAT5: { name: "Float5", type: "FLOAT5", category: "value", },
FLOAT6: { name: "Float6", type: "FLOAT6", category: "value", },
});
const ReqTypeMap = Object.fromEntries(
Object.entries(ReqType).map(([k, v]) => [v.prefix, v])
);
const ReqFlagMap = Object.fromEntries(
Object.entries(ReqFlag).map(([k, v]) => [v.prefix, v])
);
const MemSizeMap = Object.fromEntries(
[].concat(
Object.entries(MemSize).map(([k, v]) => [v.prefix, v]),
Object.entries(MemSize).map(([k, v]) => [v.prefix.toLowerCase(), v])
)
);
const FormatTypeMap = Object.fromEntries(
Object.entries(FormatType).map(([k, v]) => [v.type, v])
);
const BitProficiency = new Set([
MemSize.BIT0,
MemSize.BIT1,
MemSize.BIT2,
MemSize.BIT3,
MemSize.BIT4,
MemSize.BIT5,
MemSize.BIT6,
MemSize.BIT7,
MemSize.BITCOUNT,
]);
const PartialAccess = new Set([
MemSize.BIT0,
MemSize.BIT1,
MemSize.BIT2,
MemSize.BIT3,
MemSize.BIT4,
MemSize.BIT5,
MemSize.BIT6,
MemSize.BIT7,
MemSize.BITCOUNT,
MemSize.LOWER4,
MemSize.UPPER4,
]);
const ValueWidth = 10;
const ReqTypeWidth = Math.max(...Object.values(ReqType).map((x) => x.name.length));
const ReqFlagWidth = Math.max(...Object.values(ReqFlag).map((x) => x.name.length));
const MemSizeWidth = Math.max(...Object.values(MemSize).map((x) => x.name.length));
class LogicParseError extends Error {
constructor(type, mem) {
super(`Failed to parse ${type}: ${mem}`);
this.name = 'LogicParseError';
}
}
const OPERAND_RE = /^(([~dpbv]?)((?:0x)+[G-Z ]?|f[A-Z])(?:0x)*([0-9A-F]{1,8}))|(([fv]?)([-+]?\d+(?:\.\d+)?))|([G-Z ]?([0-9A-F]+))|({recall})$/i;
class ReqOperand
{
type;
value;
size;
constructor({ value = null, type, size = null })
{
this.value = value;
this.type = type;
this.size = size;
}
static fromString(def)
{
try
{
let match = def.match(OPERAND_RE);
// address for memory read
if (match[1])
return new ReqOperand({
value: parseInt(match[4].trim(), 16),
type: ReqTypeMap[match[2].trim()],
size: MemSizeMap[match[3].trim()],
});
// value in decimal/float
else if (match[5])
{
// force Value type if no prefix
let rtype = match[6].trim();
if (rtype == '') rtype = 'v';
return new ReqOperand({
value: +match[7].trim(),
type: ReqTypeMap[rtype.toLowerCase()],
});
}
// value in hex with size info
else if (match[8])
return new ReqOperand({
value: parseInt(match[9], 16),
type: ReqType.VALUE,
});
// recall
else if (match[10])
return new ReqOperand({ type: ReqType.RECALL, });
}
catch (e) { throw new LogicParseError('operand', def); }
}
static sameValue(a, b)
{
if (a == b || a == null || b == null) return a == b;
return a.size == b.size && a.value == b.value;
}
static equals(a, b) { return ReqOperand.sameValue(a, b) && a.type == b.type; }
maxValue()
{
if (this.type && !this.type.addr) return +this.value;
if (this.type == ReqType.RECALL) return Number.POSITIVE_INFINITY;
return this.size.maxvalue;
}
toValueString() { return this.type && this.type.addr ? ('0x' + this.value.toString(16).padStart(8, '0')) : ("" + this.value); }
toString() { return this.type == ReqType.RECALL ? this.type.prefix : this.toValueString(); }
toAnnotatedString() { return (this.type.addr ? `${this.type.name} ` : "") + this.toString(); }
toMarkdown(wReqType = ReqTypeWidth, wMemSize = MemSizeWidth, wValue = ValueWidth)
{
let value = "" + (this.value == null ? "" : this.value);
let size = this.size ? this.size.name : "";
return this.type.name.padEnd(wReqType + 1, " ") +
size.padEnd(wMemSize + 1, " ") +
this.toString().padEnd(wValue + 1);
}
toObject() { return {...this}; }
}
// reversal of comparison
const CMP_REVERSE = new Map([["=", "!="], ["!=", "="], [">", "<="], ["<", ">="], [">=", "<"], ["<=", ">"]]);
// original regex failed on "v-1"
// const REQ_RE = /^([A-Z]:)?(.+?)(?:([!<>=+\-*/&\^%]{1,2})(.+?))?(?:\.(\d+)\.)?$/;
const OPERAND_PARSING = "[~dpbvf]?(?:(?:0x)+[G-Z ]?|f[A-Z])(?:0x)*[0-9A-F]{1,8}|[fv]?[-+]?\\d+(?:\\.\\d+)?|[G-Z ]?[0-9A-F]+|{recall}";
const REQ_RE = new RegExp(`^([A-Z]:)?(${OPERAND_PARSING})(?:([!<>=+\\-*/&\\^%]{1,2})(${OPERAND_PARSING}))?(?:\\.(\\d+)\\.)?$`, "i");
class Requirement
{
flag = null;
lhs;
op = null;
rhs = null;
hits = 0;
#ref = '';
constructor({ flag = null, lhs, op = null, rhs = null, hits = 0 })
{
this.flag = flag;
this.lhs = lhs;
this.op = op;
this.rhs = rhs;
this.hits = 0;
this.#ref = crypto.randomUUID();
}
toRefString() { return `req-${this.#ref}`; }
clone() { return new Requirement({...this}); }
hasHits() { return !this.flag || !this.flag.scalable; }
canonicalize()
{
let res = this.clone();
if (res.rhs != null && res.isComparisonOperator())
if (res.lhs.type.cprio > res.rhs.type.cprio) // this is backwards
{
[res.lhs, res.rhs] = [res.rhs, res.lhs];
res.op = CMP_REVERSE.get(res.op);
}
return res;
}
isAlwaysTrue() { return this.op == '=' && ReqOperand.equals(this.lhs, this.rhs); }
isAlwaysFalse()
{
return this.op == '=' // equals cmp
&& this.lhs && !this.lhs.type.addr // lhs is a static value
&& this.rhs && !this.rhs.type.addr // rhs is a static value
&& !ReqOperand.equals(this.lhs, this.rhs); // values cant be equal
}
isComparisonOperator() { return ['=', '!=', '>', '>=', '<', '<='].includes(this.op); }
reverseComparison() { if (this.isComparisonOperator()) this.op = CMP_REVERSE.get(this.op); }
isModifyingOperator() { return this.op && !this.isComparisonOperator(); }
isTerminating() { return !this.flag || !this.flag.cmod; }
static fromString(def)
{
let req = new Requirement({});
try
{
let match = def.match(REQ_RE);
req.lhs = ReqOperand.fromString(match[2]);
if (match[1]) req.flag = ReqFlagMap[match[1]];
if (match[3])
{
req.op = match[3];
if (req.flag && req.flag.scalable && req.isComparisonOperator())
req.op = null;
else req.rhs = ReqOperand.fromString(match[4]);
}
if (match[5]) req.hits = +match[5];
}
catch (e) { throw new LogicParseError('requirement', def); }
return req;
}
toAnnotatedString() { return this.lhs.toAnnotatedString() + (this.op ? ` ${this.op} ${this.rhs.toAnnotatedString()}` : "") }
toMarkdown(wReqType, wMemSize, wValue)
{
let flag = this.flag ? this.flag.name : "";
let res = flag.padEnd(ReqFlagWidth + 1, " ");
res += this.lhs.toMarkdown(wReqType, wMemSize, wValue);
if (this.op)
{
res += this.op.padEnd(4, " ");
res += this.rhs.toMarkdown(wReqType, wMemSize, wValue);
if (!this.flag || !this.flag.scalable) res += "(" + this.hits + ")";
}
return res;
}
}
class Logic
{
groups = [];
mem = null;
value = false;
constructor()
{
}
static fromString(def, value = null)
{
let logic = new Logic();
try
{
logic.value = value == null ? def.includes('$') : !!value;
for (const [i, g] of def.split(logic.value ? "$" : /(?<!0x)S/).entries())
{
let group = [];
if (g.length > 0) // some sets have empty core groups
for (const [j, req] of g.split(/_/).entries())
group.push(Requirement.fromString(req));
logic.groups.push(group);
}
logic.mem = def;
}
catch (e) { throw new LogicParseError('logic', def); }
return logic;
}
getAddresses()
{
return this.groups.reduce((ia, ie) => ia.concat(
ie.reduce((ja, je, i, a) => {
let p = i == 0 ? null : a[i-1].flag;
return ja.concat({ opd: je.lhs, pre: p }, { opd: je.rhs, pre: p });
}, [])
), [])
.filter(({ pre }) => pre != ReqFlag.ADDADDRESS) // remove everything following an AddAddress
.filter(({ opd }) => opd && opd.type && opd.type.addr) // keep only address reads
.map(({ opd }) => opd.value);
}
getMemoryLookups()
{
let virt = new Set();
for (const [gi, g] of this.groups.entries())
{
let prefix = '';
for (const [ri, req] of g.entries())
{
if (req.flag == ReqFlag.ADDADDRESS)
prefix += req.lhs.toString() + (!req.rhs ? '' : (req.op + req.rhs.toString())) + ':';
else
{
if (req.lhs && req.lhs.type.addr) virt.add(prefix + req.lhs.toString());
if (req.rhs && req.rhs.type.addr) virt.add(prefix + req.rhs.toString());
prefix = '';
}
}
}
return virt;
}
getFlags() { return this.groups.reduce((ia, ie) => ia.concat(ie.map(x => x.flag)), []).filter(x => x); }
toMarkdown()
{
let output = "";
let i = 0;
const wValue = Math.max(...this.getOperands().map((x) => x.toValueString().length));
const wReqType = Math.max(...this.getTypes().map((x) => x.name.length));
const wMemSize = Math.max(...this.getMemSizes().map((x) => x.name.length));
for (const g of this.groups)
{
output += i == 0 ? "### Core\n" : `### Alt ${i}\n`;
output += "```\n";
let j = 1;
for (const req of g)
{
output += new String(j).padStart(3, " ") + ": ";
output += req.toMarkdown(wReqType, wMemSize, wValue);
output += "\n";
j += 1;
}
output += "```\n";
i += 1;
}
return output;
}
}
// Port of LogicFormatter.cs and ConditionFormatter.cs.
class LogicFormatter
{
static formatDisplayValue(operand, showDecimal, sizeReference = "")
{
if (!operand || operand.value === null) return "";
// Logic to handle Values vs Addresses/Floats
// Since operand.value in JS is usually a Number, we handle it directly
if (typeof operand.value === 'number')
{
if (operand.type === ReqType.VALUE)
{
if (showDecimal) return operand.value.toString();
const padding = LogicFormatter.getPaddingForSize(sizeReference);
const mask = LogicFormatter.getMaskForSize(sizeReference);
// Handle potential negative masking or large numbers
let val = operand.value;
if (mask !== -1) val = val & mask;
// Convert to unsigned for hex display if negative
if (val < 0) val = val >>> 0;
return "0x" + val.toString(16).padStart(padding, '0');
}
else if (operand.type !== ReqType.FLOAT)
{
return "0x" + operand.value.toString(16).padStart(8, '0');
}
}
if (operand.type === ReqType.FLOAT)
{
// operand.value might be string or number
return operand.value.toString();
}
return operand.value.toString();
}
static getPaddingForSize(size)
{
if (!size) return 8;
const name = size.name || size;
if (name.includes("8-bit") || name.includes("Bit") || name.includes("4")) return 2;
if (name.includes("16-bit")) return 4;
if (name.includes("24-bit")) return 6;
return 8;
}
static getMaskForSize(size)
{
if (!size) return -1;
const name = size.name || size;
if (name.includes("8-bit") || name.includes("Bit") || name.includes("4")) return 0xFF;
if (name.includes("16-bit")) return 0xFFFF;
if (name.includes("24-bit")) return 0xFFFFFF;
return -1;
}
static normalizeAddress(address)
{
if (address === null || address === undefined) return "";
// In JS, address is typically a Number. If so, return 0xString
if (typeof address === 'number') return "0x" + address.toString(16).toLowerCase();
let clean = address.toString().trim();
if (clean.toLowerCase().startsWith("0x")) clean = clean.substring(2);
return "0x" + clean.toLowerCase();
}
}
class ConditionFormatter
{
// Helper to resolve "refer to $0x..." redirects
static getEffectiveNote(notesLookup, addrVal)
{
// Safety check for notesLookup type
let note = null;
if (notesLookup && typeof notesLookup.get === 'function') {
note = notesLookup.get(addrVal);
} else if (Array.isArray(notesLookup)) {
// Fallback if notesLookup is a plain array
note = notesLookup.find(n => (n.contains && n.contains(addrVal)) || n.addr === addrVal);
}
let redirects = 0;
while (note && redirects < 5)
{
const text = note.note || "";
const match = text.match(/refer to \$0x([0-9a-fA-F]+)/i);
if (match)
{
const targetAddr = parseInt(match[1], 16);
let targetNote = null;
if (notesLookup && typeof notesLookup.get === 'function') {
targetNote = notesLookup.get(targetAddr);
} else if (Array.isArray(notesLookup)) {
targetNote = notesLookup.find(n => (n.contains && n.contains(targetAddr)) || n.addr === targetAddr);
}
if (targetNote)
{
note = targetNote;
redirects++;
continue;
}
}
break;
}
return note;
}
// Helper: Parse specific value from text (Updated for Floats)
static parseValueFromText(text, targetVal) {
if (!text) return null;
const lines = text.split(/\r\n|\r|\n/);
// Regex matches:
// 1. "0x10 = Label" (Hex)
// 2. "16 : Label" (Dec)
// 3. "0.5 = Label" (Float)
// 4. "-1.0 = Label" (Signed Float)
const regex = /^\s*((?:0x[0-9a-fA-F]+)|(?:[-+]?[0-9]*\.?[0-9]+))\s*[:=]\s*(.+)$/;
// Tolerance for float comparison
const EPSILON = 0.000001;
for (const line of lines) {
const match = line.match(regex);
if (match) {
const rawVal = match[1];
let lineVal;
if (rawVal.toLowerCase().startsWith("0x")) {
lineVal = parseInt(rawVal, 16);
} else if (rawVal.includes('.')) {
lineVal = parseFloat(rawVal);
} else {
lineVal = parseInt(rawVal, 10);
}
// Comparison logic
if (typeof targetVal === 'number') {
if (!Number.isInteger(targetVal) || !Number.isInteger(lineVal)) {
if (Math.abs(lineVal - targetVal) < EPSILON) return match[2].trim();
} else {
if (lineVal === targetVal) return match[2].trim();
}
}
}
}
return null;
}
// Helper: Parse Bit label
static parseBitLabelFromText(text, bitIndex) {
if (!text) return null;
const lines = text.split(/\r\n|\r|\n/);
const regex = new RegExp(`^\\s*Bit\\s*${bitIndex}\\s*[:=]\s*(.+)`, "i");
for (const line of lines) {
const match = line.match(regex);
if (match) return match[1].trim();
}
return null;
}
// Resolve Enum OR Bit Values
static resolveEnum(value, contextAddr, contextSize, notesLookup, chainInfo = [])
{
if (contextAddr === null || contextAddr === undefined) return null;
// 1. Determine Base Address and Offsets
let baseAddr = contextAddr;
let offsets = [];
if (chainInfo && chainInfo.length > 0) {
const baseObj = chainInfo.find(x => x.type === 'base');
if (baseObj) {
baseAddr = baseObj.value;
offsets = chainInfo.filter(x => x.type === 'offset').map(x => x.value);
offsets.push(contextAddr);
}
}
// 2. Get the Base Note
const note = ConditionFormatter.getEffectiveNote(notesLookup, baseAddr);
if (!note) return null;
// 3. Pointer Traversal Logic
let targetNode = null;
let foundNoteContent = null;
if (offsets.length === 0) {
if (note.noteNodes) {
targetNode = note.noteNodes.find(n => n.indentLevel === -2) || note.noteNodes[0];
}
if (!targetNode) foundNoteContent = note.note;
} else if (note.noteNodes) {
let currentLevelNodes = note.noteNodes.filter(n => n.indentLevel !== -2 && (!n.parent || n.parent.indentLevel === -1));
const parseOff = (s) => {
let clean = s.replace('+', '').replace('-', '').trim();
if (clean.startsWith("0x")) clean = clean.substring(2);
let v = parseInt(clean, 16);
if (s.includes('-')) v = -v;
return v;
};
for (let i = 0; i < offsets.length; i++) {
const off = offsets[i];
let match = null;
for (const n of currentLevelNodes) {
const nOff = parseOff(n.offset);
if (off >= nOff && off < nOff + n.size) {
match = n;
break;
}
}
if (match) {
if (i === offsets.length - 1) targetNode = match;
else currentLevelNodes = match.children;
} else {
break;
}
}
}
if (targetNode) foundNoteContent = targetNode.content;
// 4. BITFIELD LOGIC
if (contextSize && contextSize.name && contextSize.name.startsWith("Bit")) {
const bitChar = contextSize.name.charAt(contextSize.name.length - 1);
const bitIndex = parseInt(bitChar, 10);
if (!isNaN(bitIndex)) {
if (value === 0) return "false";
if (value === 1) {
if (foundNoteContent) {
const label = ConditionFormatter.parseBitLabelFromText(foundNoteContent, bitIndex);
if (label) return label;
}
return "true";
}
}
}
// 5. ENUM LOGIC
// Only use pre-parsed if not float
if (offsets.length === 0 && note.enum && Number.isInteger(value)) {
const match = note.enum.find(e => e.value === value);
if (match) return match.meaning;
}
if (foundNoteContent) {
return ConditionFormatter.parseValueFromText(foundNoteContent, value);
}
return null;
}
static resolveAlias(address, group, rowIndex, notesLookup, rangeCache)
{
function parseHex(s) {
if (typeof s === 'number') return s;
if (!s) return -1;
const clean = s.replace("0x", "").trim().replace(/[^0-9A-Fa-f]/g, "");
if (!clean) return -1;
const val = parseInt(clean, 16);
return isNaN(val) ? -1 : val;
}
const targetVal = parseHex(address);
if (targetVal === -1) return ""; // Safety exit
const conditions = group;
if (conditions && rowIndex > 0 && rowIndex < conditions.length)
{
const chainStack = [];
let scan = rowIndex - 1;
while (scan >= 0)
{
if (scan >= conditions.length) {
scan--;
continue;
}
const prevCond = conditions[scan];
if (prevCond.flag && prevCond.flag.name === "AddAddress")
{
chainStack.push(prevCond.lhs.value);
scan--;
}
else break;
}
if (chainStack.length > 0)
{
const baseAddrVal = chainStack.pop();
const normalizedBase = LogicFormatter.normalizeAddress(baseAddrVal);
const baseAddrNum = parseHex(normalizedBase);
const baseNote = ConditionFormatter.getEffectiveNote(notesLookup, baseAddrNum);
if (baseNote && baseNote.noteNodes)
{
let currentLevelNodes = baseNote.noteNodes.filter(n => n.indentLevel !== -2 && (!n.parent || n.parent.indentLevel === -1));
let chainValid = true;
while (chainStack.length > 0)
{
const offsetVal = chainStack.pop();
let match = null;
for (const node of currentLevelNodes)
{
let nodeOff = parseHex(node.offset.replace('+', '').replace('-', ''));
if (node.offset.includes('-')) nodeOff = -nodeOff;
if (offsetVal >= nodeOff && offsetVal < nodeOff + node.size)
{
match = node;
break;
}
}
if (match) currentLevelNodes = match.children;
else { chainValid = false; break; }
}
if (chainValid && targetVal !== -1)
{
for (const node of currentLevelNodes)
{
let nodeOff = parseHex(node.offset.replace('+', '').replace('-', ''));
if (node.offset.includes('-')) nodeOff = -nodeOff;
if (targetVal >= nodeOff && targetVal < nodeOff + node.size)
{
let desc = node.description.replace(/\[.*?\]/g, "").trim();
const delta = targetVal - nodeOff;
if (delta > 0)
{
const suffix = ` +0x${delta.toString(16).toUpperCase()}`;
if (!desc.toLowerCase().endsWith(suffix.toLowerCase()))
desc += suffix;
}
return desc;
}
}
}
}
}
}
const directNote = ConditionFormatter.getEffectiveNote(notesLookup, targetVal);
if (directNote && directNote.noteNodes)
{
const rootNode = directNote.noteNodes.find(n => n.indentLevel === -2) || directNote.noteNodes[0];
if (rootNode)
{
let desc = rootNode.description;
if (!desc || desc.toLowerCase() === "full note")
{
if (rootNode.content)
desc = rootNode.content.split(/\r\n|\r|\n/)[0] || "";
}
desc = desc.replace(/\[.*?\]/g, (m) => {
if (m.toLowerCase().includes("pointer")) return "[Pointer]";
return "";
}).trim();
// Calculate offset from base note address for direct notes
const delta = targetVal - directNote.addr;
if (delta > 0)
{
const suffix = ` +0x${delta.toString(16).toUpperCase()}`;
if (!desc.toLowerCase().endsWith(suffix.toLowerCase()))
desc += suffix;
}
return desc.replace(/\s{2,}/g, " ");
}
}
if (rangeCache && targetVal !== -1)
{
const match = rangeCache.find(r => targetVal >= r.start && targetVal < r.end);
if (match && match.node)
{
let desc = match.node.description;
if (!desc || desc.toLowerCase() === "full note")
{
desc = match.node.content.split(/\r\n|\r|\n/)[0] || "";
}
desc = desc.replace(/\[.*?\]/g, (m) => {
if (m.toLowerCase().includes("pointer")) return "[Pointer]";
return "";
}).trim();
desc = desc.replace(/\s{2,}/g, " ");
const delta = targetVal - match.start;
if (delta > 0)
{
const suffix = ` +0x${delta.toString(16).toUpperCase()}`;
if (!desc.toLowerCase().endsWith(suffix.toLowerCase()))
desc += suffix;
}
return desc;
}
}
return "";
}
}
function getOperands(groups) {
return groups.reduce((ia, ie) => ia.concat(
ie.reduce((ja, je) => ja.concat(je.lhs, je.rhs), [])
), []).filter(x => x);
}
function getMemSizes(operands) {
return operands.map(x => x.size).filter(x => x);
}
function getTypes(operands) {
return operands.map(x => x.type).filter(x => x);
}
module.exports = { LogicParseError, MemSize, Logic, FormatTypeMap, BitProficiency, ReqFlag, ReqType, getMemSizes, getTypes, getOperands, PartialAccess, ReqOperand, FormatType, Requirement };