-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.mjs
More file actions
4189 lines (3992 loc) · 214 KB
/
Copy pathindex.mjs
File metadata and controls
4189 lines (3992 loc) · 214 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
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import Parser from 'tree-sitter';
import C from 'tree-sitter-c';
// Usage: node index.mjs <outDir> <sourceRoot1> [<sourceRoot2> ...]
const [outDir, ...roots] = process.argv.slice(2);
if (!outDir || roots.length === 0) {
console.error('Usage: node index.mjs <outDir> <sourceRoot1> [<sourceRoot2> ...]');
process.exit(1);
}
const parser = new Parser();
parser.setLanguage(C);
// ---------------------------------------------------------------------------
// Generic tree helpers
// ---------------------------------------------------------------------------
function walkDir(dir, exts, out = []) {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) walkDir(full, exts, out);
else if (exts.includes(path.extname(entry.name))) out.push(full);
}
return out;
}
function walkTree(node, cb) {
cb(node);
for (const child of node.children) walkTree(child, cb);
}
function childrenForField(node, field) {
const out = [];
const cursor = node.walk();
if (cursor.gotoFirstChild()) {
do {
if (cursor.currentFieldName === field) out.push(cursor.currentNode);
} while (cursor.gotoNextSibling());
}
return out;
}
function findNameInDeclarator(node) {
if (!node) return null;
if (node.type === 'identifier') return node.text;
const inner = node.childForFieldName('declarator');
if (inner) return findNameInDeclarator(inner);
for (const child of node.children) {
const found = findNameInDeclarator(child);
if (found) return found;
}
return null;
}
// node-tree-sitter returns a fresh wrapper object on every accessor call, so
// two references to the same syntax node are never `===`; compare .id instead.
const sameNode = (a, b) => !!a && !!b && a.id === b.id;
// Classifies a call_expression's own `function` node: a plain name
// (`foo()`) resolves directly against the project's real functions later,
// same as before — but `obj->cb()` / `obj.cb()` (field_expression),
// `table[i]()` (subscript_expression) and `(*fp)()` (a dereferenced
// pointer) never have, and *specifically because they're indirect never
// will have, a plain identifier to look up: the call graph used to just
// drop these on the floor. No type information is tracked anywhere in this
// analyzer, so there's no way to know *which* struct/array a given
// `->field`/`[i]` targets — the same "key by name alone, union every
// project-wide match" trade-off already made for periph/DMA resolution
// (resolveAddrExpr) applies here too: an indirect call's target is
// resolved by matching its field/variable name against every assignment of
// that same name anywhere in the project (collectFpAssignments + the
// fpTargets map built during the main scan), not by tracing the actual
// pointer's type.
function resolveCallTarget(fnNode) {
let n = fnNode;
while (n && n.type === 'parenthesized_expression') n = n.namedChildren[0];
if (n && n.type === 'pointer_expression' && n.childForFieldName('operator')?.text === '*') {
n = n.childForFieldName('argument');
while (n && n.type === 'parenthesized_expression') n = n.namedChildren[0];
}
if (!n) return null;
if (n.type === 'identifier') return { kind: 'direct', name: n.text };
if (n.type === 'field_expression') {
const field = n.childForFieldName('field')?.text;
return field ? { kind: 'indirect', key: field } : null;
}
if (n.type === 'subscript_expression') {
let base = n.childForFieldName('argument');
while (base && base.type === 'parenthesized_expression') base = base.namedChildren[0];
return base && base.type === 'identifier' ? { kind: 'indirect', key: base.text } : null;
}
return null;
}
// Every "name (whether a plain variable, or the last field of a `.`/`->`
// access) was assigned a real function's name" fact in one file — the raw
// material for fpTargets (built project-wide once functionsByName exists to
// filter these down to real functions). Deliberately walks the *whole* file
// (translation_unit), not just function bodies: the classic C pattern this
// exists for — `static const Ops my_ops = { .read = my_read, ... };` —
// lives at file scope, outside any function. No type tracking here either,
// same as resolveCallTarget: `key` is just the bare variable/field name, so
// `X.read = a;` and `Y.read = b;` for two unrelated struct types both feed
// the same `read` bucket — an accepted false-positive risk, not a bug (same
// trade-off as periph resolution elsewhere).
function collectFpAssignments(root) {
const out = [];
walkTree(root, n => {
if (n.type === 'assignment_expression') {
if (n.childForFieldName('operator')?.text !== '=') return;
const right = n.childForFieldName('right');
if (!right || right.type !== 'identifier') return;
let left = n.childForFieldName('left');
if (!left) return;
// `table[2] = target;` — peel `[index]` layers the same way
// resolveCallTarget does for the read side (`table[i]()`), so the two
// sides agree on the same base-name key.
while (left && left.type === 'subscript_expression') left = left.childForFieldName('argument');
while (left && left.type === 'parenthesized_expression') left = left.namedChildren[0];
if (!left) return;
if (left.type === 'identifier') out.push({ key: left.text, valueName: right.text });
else if (left.type === 'field_expression') {
const field = left.childForFieldName('field')?.text;
if (field) out.push({ key: field, valueName: right.text });
}
return;
}
if (n.type === 'init_declarator') {
const value = n.childForFieldName('value');
if (value && value.type === 'identifier') {
const nm = findNameInDeclarator(n.childForFieldName('declarator'));
if (nm) out.push({ key: nm, valueName: value.text });
}
return;
}
if (n.type === 'initializer_pair') {
// `{ .read = my_read, .write = my_write }` — the callback-table
// pattern. Only the single-level `.field = value` shape is handled
// (childForFieldName only ever returns the *first* designator, so a
// nested `.a.b = x`/`.arr[2].field = x` designator falls through
// unmatched below rather than being misread) — good enough for the
// common case without pretending to parse the general one.
const value = n.childForFieldName('value');
if (!value || value.type !== 'identifier') return;
const designator = n.childForFieldName('designator');
if (designator && designator.type === 'field_designator') {
const fieldIdent = designator.namedChildren.find(c => c.type === 'field_identifier');
if (fieldIdent) out.push({ key: fieldIdent.text, valueName: value.text });
}
}
});
return out;
}
function insideFunction(node) {
for (let p = node.parent; p; p = p.parent) {
if (p.type === 'function_definition') return true;
}
return false;
}
// ---------------------------------------------------------------------------
// Extraction
// ---------------------------------------------------------------------------
function extractIncludes(root) {
const includes = [];
walkTree(root, node => {
if (node.type === 'preproc_include') {
const target = node.namedChildren.find(
c => c.type === 'string_literal' || c.type === 'system_lib_string',
);
if (target) {
const raw = target.text.replace(/^["<]|[">]$/g, '');
includes.push({ raw, isSystem: target.type === 'system_lib_string' });
}
}
});
return includes;
}
function extractFunctions(root) {
const funcs = [];
walkTree(root, node => {
if (node.type === 'function_definition') {
const declarator = node.childForFieldName('declarator');
const name = findNameInDeclarator(declarator);
if (name) funcs.push({ name, node });
}
});
return funcs;
}
// --- doc comments -----------------------------------------------------------
// Convention: a description belongs to a declaration only if it is *adjacent* —
// either a trailing comment on the same line, or comment line(s) directly
// above with no blank line in between. A comment that shares its line with
// code (trailing comment of the previous statement) is never picked up.
function cleanComment(text) {
const lines = text.split('\n').map(l =>
l.replace(/^\s*\/\*+/, '').replace(/\*+\/\s*$/, '')
.replace(/^\s*\/\/+/, '').replace(/^\s*\*+(?!\/)/, '').trim(),
).filter(l => l && !/^[=\-_~*#+.\s]+$/.test(l));
return lines.join(' ').replace(/\s+/g, ' ')
.replace(/^[@\\]fn\s+\S+\s*/i, '')
.replace(/^[@\\]brief\s*/i, '').trim();
}
function buildCommentIndex(root, srcLines) {
const byEndRow = new Map();
const byStartRow = new Map();
walkTree(root, n => {
if (n.type !== 'comment') return;
byStartRow.set(n.startPosition.row, n);
// only "own-line" comments may serve as a preceding description
const before = (srcLines[n.startPosition.row] || '').slice(0, n.startPosition.column);
if (before.trim() === '') byEndRow.set(n.endPosition.row, n);
});
return { byEndRow, byStartRow };
}
function docCommentFor(node, idx, { allowTrailing = false } = {}) {
if (allowTrailing) {
const t = idx.byStartRow.get(node.endPosition.row);
if (t && t.startIndex >= node.endIndex) {
const s = cleanComment(t.text);
if (s) return s;
}
}
const parts = [];
let row = node.startPosition.row - 1;
while (parts.length < 8) {
const c = idx.byEndRow.get(row);
if (!c) break;
parts.unshift(c.text);
row = c.startPosition.row - 1;
}
// a run of // lines containing a decorative rule (// ====) is a section
// banner for the code below, not a description of this one declaration
if (parts.length && parts.every(p => p.startsWith('//'))) {
const hasRule = parts.some(p => {
const t = p.replace(/^\/\/+/, '').trim();
return t !== '' && /^[=\-_~*#+.]+$/.test(t);
});
if (hasRule) return '';
}
return cleanComment(parts.join('\n'));
}
// A declarator declares a *function* (prototype) when, after unwrapping
// pointers/arrays, we hit a function_declarator whose own declarator is a
// bare identifier. `void (*cb)(void)` is a function-pointer VARIABLE: there
// the function_declarator wraps a parenthesized_declarator instead.
function isFunctionDeclarator(decl) {
let d = decl;
if (d && d.type === 'init_declarator') d = d.childForFieldName('declarator');
while (d) {
if (d.type === 'function_declarator') {
const inner = d.childForFieldName('declarator');
return !!inner && inner.type === 'identifier';
}
if (d.type === 'pointer_declarator' || d.type === 'array_declarator') {
d = d.childForFieldName('declarator');
continue;
}
if (d.type === 'parenthesized_declarator') return false;
break;
}
return false;
}
function typeTextOf(declNode) {
const t = declNode.childForFieldName('type');
if (!t) return '';
let text = t.text.replace(/\s+/g, ' ');
if (text.length > 28) text = text.slice(0, 25) + '...';
return text;
}
// File-scope variables: definitions and extern declarations.
function extractFileScopeVars(root, commentIdx) {
const defs = [];
const externs = [];
walkTree(root, node => {
if (node.type !== 'declaration' || insideFunction(node)) return;
const storage = node.namedChildren
.filter(c => c.type === 'storage_class_specifier')
.map(c => c.text);
if (storage.includes('typedef')) return;
const isExtern = storage.includes('extern');
const isStatic = storage.includes('static');
const isVolatile = /\bvolatile\b/.test(node.text.split('=')[0]);
const typeText = typeTextOf(node);
const desc = docCommentFor(node, commentIdx, { allowTrailing: true });
for (const d of childrenForField(node, 'declarator')) {
if (isFunctionDeclarator(d)) continue;
const name = findNameInDeclarator(d);
if (!name) continue;
(isExtern ? externs : defs).push({ name, isStatic, isVolatile, typeText, desc });
}
});
return { defs, externs };
}
// How is this identifier used: read, write, or both?
// fold a new access mode into an existing one: r + w (in either order) => rw.
const mergeMode = (prev, m) => (!prev ? m : prev === m ? prev : 'rw');
// CMSIS/HAL bit-flag macros are always SHOUTING_SNAKE_CASE — a local
// variable or parameter is not (`byte`, `data`, `len`). Used to keep
// collectIdentifiers from misattributing a plain data value as a "flag" once
// flag extraction covers plain `=` assignments too (see analyzeFunction's
// third addFlagNames branch below) — `USART1->DR = byte` must never grow a
// fake "byte" flag entry the way `CCR = DMA_CCR_MINC | DMA_CCR_EN` correctly
// grows `MINC`/`EN` ones.
const MACRO_CONST_RE = /^[A-Z_][A-Z0-9_]*$/;
// every named identifier leaf under a (possibly grouped/OR'd) expression,
// e.g. collectIdentifiers for `(FLAG1 | FLAG2)` -> {FLAG1, FLAG2} — used to
// pull every flag name out of a bitmask test regardless of how many bits it
// checks at once. Only collects SHOUTING_SNAKE_CASE leaves (see
// MACRO_CONST_RE) — a lowercase identifier is a variable, never a flag.
function collectIdentifiers(node, out) {
if (node.type === 'identifier') {
if (MACRO_CONST_RE.test(node.text)) out.add(node.text);
return;
}
if (node.type === 'parenthesized_expression' || node.type === 'binary_expression') {
for (const c of node.namedChildren) collectIdentifiers(c, out);
}
}
// merges a 'w'-direction flag's set/clear polarity into an accumulating Map
// (flagName -> 'set'|'clear'|'both') — 'set' from `|= FLAG` and the one-shot
// `field = FLAG1 | FLAG2 | ...` idiom, 'clear' from `field &= ~FLAG`. The same
// bit seen as both within the merge (a channel disabled then immediately
// re-armed in the same function, e.g. u1_kick's `CCR &= ~DMA_CCR_EN; ...;
// CCR |= DMA_CCR_EN;`) collapses to 'both' rather than picking one arbitrarily
// — periphDirDetail treats 'both' as "ends up enabled", same as a plain 'set'.
function mergeFlagPolarity(map, name, polarity) {
const prev = map.get(name);
map.set(name, prev && prev !== polarity ? 'both' : polarity);
}
function classifyAccess(id) {
let n = id;
while (n.parent) {
const p = n.parent;
if (p.type === 'assignment_expression') {
if (sameNode(p.childForFieldName('left'), n)) {
const opNode = p.children.find(c => !c.isNamed && c.text.endsWith('='));
return opNode && opNode.text !== '=' ? 'rw' : 'w';
}
return 'r';
}
if (p.type === 'update_expression') return 'rw'; // ++ / --
if (p.type === 'pointer_expression') {
const op = p.children[0] ? p.children[0].text : '*';
// &x: address escapes, assume read+write; *p: the pointer itself is read
return op === '&' ? 'rw' : 'r';
}
if (p.type === 'subscript_expression') {
if (sameNode(p.childForFieldName('argument'), n)) { n = p; continue; }
return 'r'; // inside the [index]
}
if (p.type === 'field_expression') {
if (sameNode(p.childForFieldName('argument'), n)) { n = p; continue; }
return 'r';
}
if (p.type === 'parenthesized_expression') { n = p; continue; }
return 'r';
}
return 'r';
}
// Bare DMA controller instance (DMA1, DMA2 — never DMA1_Channel4, that's its
// own instance). Declared up here, ahead of fileRecords/peripherals below,
// because analyzeFunction (which needs it) runs while fileRecords is still
// being built. See the fuller comment by allDerefNames/dmaChannelTarget.
const DMA_BUS_RE = /^DMA[0-9]+$/;
function analyzeFunction(funcNode) {
const declarator = funcNode.childForFieldName('declarator');
const locals = new Set();
// a local pointer's own initializer, resolved one level deep — see
// resolveLocalAlias — so `X->CMAR = m->data` can be traced through
// `U1Msg *m = &u1_q[u1_q_tail];` back to `u1_q`, the same way a direct
// `X->CMAR = u1_rx_buf` already resolves. name -> {kind, name/key, field}
// Orthogonal to resolveSymbolicRef below (this is CPAR/CMAR's OWN "what
// does this pointer ultimately point at, var or periph" question, not
// periph-base resolution) — kept as its own separate mechanism.
const localAliases = new Map();
// This function's own local array literals (`T *const PORTS[] = {...};`)
// and locals resolved to a peripheral candidate set via resolveSymbolicRef
// (`GPIO_TypeDef *p = port_reg(...);` or `= PORTS[i];`) — both feed the
// `scope` resolveSymbolicRef needs for everything below. Built in
// declaration order in the SAME walk, so a local may reference an EARLIER
// one (never a later one — matches normal C declare-before-use).
const localArrays = new Map();
const localPeriphVars = new Map();
const scope = { locals, localArrays, localVars: localPeriphVars };
if (declarator) {
walkTree(declarator, n => {
if (n.type === 'parameter_declaration') {
const nm = findNameInDeclarator(n.childForFieldName('declarator'));
if (nm) locals.add(nm);
}
});
}
const body = funcNode.childForFieldName('body');
if (body) {
walkTree(body, n => {
if (n.type === 'declaration') {
for (const d of childrenForField(n, 'declarator')) {
const nm = findNameInDeclarator(d);
if (nm) locals.add(nm);
if (nm && d.type === 'init_declarator') {
const value = d.childForFieldName('value');
const ref = value && resolveAddrExpr(value);
if (ref) localAliases.set(nm, ref);
if (value && value.type === 'initializer_list' && value.namedChildren.length
&& value.namedChildren.every((it) => it.type === 'identifier' && MACRO_CONST_RE.test(it.text))) {
localArrays.set(nm, new Set(value.namedChildren.map((it) => it.text)));
} else if (value) {
const resolved = resolveSymbolicRef(value, scope);
if (resolved.size) localPeriphVars.set(nm, resolved);
}
}
}
}
});
}
const calls = new Set();
const indirectCalls = new Set(); // field/subscript/deref call-target keys — see resolveCallTarget
// raw first-argument text of calls that arm an NVIC interrupt line, e.g.
// "DMA1_Channel2_IRQn" from NVIC_EnableIRQ(DMA1_Channel2_IRQn)
const armCalls = new Set();
// identifiers used as the base of an arrow access (`X->field`) and never
// otherwise declared in the scanned sources — the CMSIS/HAL convention for
// a peripheral register block (`#define DMA1_Channel2 ((...*)DMA1_Channel2_BASE)`
// lives in a vendor header we don't parse, so these names never resolve to
// a real variable; that absence is itself the signal that flags them as
// peripheral candidates in pass 2, not a naming-convention guess
const derefNames = new Set();
// per-register breakdown behind each derefName: which fields of the block are
// touched and how (`UART2->CR1 |= x` -> UART2: { CR1: 'rw' }). derefNames
// still flags the block as a peripheral candidate in pass 2; this keeps the
// field that pass used to throw away, so a reader of DR and a writer of CR1
// on the same UART2 stay distinguishable.
const derefFields = new Map(); // name -> Map(field -> 'r' | 'w' | 'rw')
// named bits behind a register access, split by which mode they came in as
// — read-tested (`if (X->SR & USART_SR_RXNE)`, how ISR bodies near-
// universally spell "which interrupt source is this") vs write-set/cleared
// (`X->CCR |= DMA_CCR_EN` / `X->CCR &= ~DMA_CCR_EN`) — a register touched
// via two different bits in two different places should read as two
// different things, not collapse to one anonymous "CCR: чтение/запись".
// name -> Map(field -> { r: Set(flag name), w: Set(flag name) })
const derefFlags = new Map();
// a DMA channel's own address registers (`CPAR`/`CMAR`) resolved to
// *what* they point at, when the right-hand side of a plain `X->CPAR = ...`
// assignment is simple enough to tell statically — `&PERIPH->field` names a
// peripheral, a bare identifier or `&identifier` names a global/static var.
// Anything else (a local pointer alias, e.g. `X->CMAR = (uint32_t)m->data`
// where `m` points into a runtime queue slot) is left unresolved — there's
// no attempt to trace local pointer assignments. See resolveAddrExpr.
// name -> Map(field -> { kind: 'var' | 'periph', name })
const derefAddrRefs = new Map();
const access = new Map(); // name -> { r, w }
const NVIC_ARM_RE = /^(HAL_|LL_)?NVIC_EnableIRQ$/;
// Records one `NAME->field` dereference — `p` is the `->` field_expression
// itself. Shared by the direct case below (NAME is a bare identifier, the
// common path — `p`'s own argument IS `n`) and the config-table-array case
// (NAME is one of several candidates resolved from ARRAY_FIELD_PERIPHS,
// `p`'s argument is a whole `ARR[i].field` chain instead — see that map's
// own doc comment). Pulled out of the walkTree callback below so both
// sites can call it without duplicating this logic.
function recordDeref(name, field, p, mode) {
derefNames.add(name);
if (!field) return;
// named bits behind this access, split by which mode they came in as —
// 'r' from `X->field & FLAG` (either operand order, tests a bit), 'w'
// from `X->field |= FLAG` (sets), `X->field &= ~FLAG` (clears), or a
// plain `X->field = FLAG1 | FLAG2 | ...` (a one-shot full-register
// config write). `w`'s per-flag value is a Map(flagName ->
// 'set'|'clear'|'both'), not a Set — same flag name can mean opposite
// things depending on whether it came in via `|=` (arm) or `&= ~`
// (disarm); `r` stays a plain Set (a bit *test* has no set/clear
// polarity). `polarity` is only meaningful when kind === 'w'.
function addFlagNames(kind, node, polarity) {
const flagNames = new Set();
collectIdentifiers(node, flagNames);
if (!flagNames.size) return;
let flagMap = derefFlags.get(name);
if (!flagMap) { flagMap = new Map(); derefFlags.set(name, flagMap); }
let perKind = flagMap.get(field);
if (!perKind) { perKind = { r: new Set(), w: new Map() }; flagMap.set(field, perKind); }
if (kind === 'w') {
for (const fl of flagNames) mergeFlagPolarity(perKind.w, fl, polarity);
} else {
for (const fl of flagNames) perKind.r.add(fl);
}
}
// `X->field |= FLAG` / `X->field &= ~FLAG` is the universal set/clear-a-
// bit idiom (arm/disarm, enable/disable) — hardware-wise a read-modify-
// write, but nothing is semantically *read* here: nobody downstream
// branches on the bit this statement itself just set. Field-level mode
// is downgraded to plain 'w' for exactly this idiom so it doesn't
// masquerade as a read of the register.
let fieldMode = mode;
const parent = p.parent;
const isSetClearIdiom = parent && parent.type === 'assignment_expression'
&& sameNode(parent.childForFieldName('left'), p)
&& (() => {
const op = parent.children.find(c => !c.isNamed && c.text.endsWith('='))?.text;
const right = parent.childForFieldName('right');
if (op === '|=' && right) return true;
if (op === '&=' && right && right.type === 'unary_expression'
&& right.children[0]?.text === '~') return true;
return false;
})();
if (isSetClearIdiom) fieldMode = 'w';
let fm = derefFields.get(name);
if (!fm) { fm = new Map(); derefFields.set(name, fm); }
fm.set(field, mergeMode(fm.get(field), fieldMode));
if (parent && parent.type === 'binary_expression' && parent.childForFieldName('operator')?.text === '&') {
const left = parent.childForFieldName('left'), right = parent.childForFieldName('right');
const other = sameNode(left, p) ? right : (sameNode(right, p) ? left : null);
if (other) addFlagNames('r', other);
} else if (parent && parent.type === 'assignment_expression' && sameNode(parent.childForFieldName('left'), p)) {
const op = parent.children.find(c => !c.isNamed && c.text.endsWith('='))?.text;
const right = parent.childForFieldName('right');
if (op === '|=' && right) {
addFlagNames('w', right, 'set');
} else if (op === '&=' && right && right.type === 'unary_expression'
&& right.children[0]?.text === '~') {
addFlagNames('w', right.childForFieldName('argument'), 'clear');
} else if (op === '=' && right) {
addFlagNames('w', right, 'set');
if (field === 'CPAR' || field === 'CMAR') {
const ref = resolveLocalAlias(resolveAddrExpr(right), locals, localAliases);
if (ref) {
let am = derefAddrRefs.get(name);
if (!am) { am = new Map(); derefAddrRefs.set(name, am); }
am.set(field, ref);
}
}
}
}
}
// Records a periph access resolved not to one certain name but to a whole
// candidate SET (anything resolveSymbolicRef returns more than one — or
// even exactly one non-obvious — answer for). Pass 2 decides var-vs-
// periph by walking fn.access's own keys, falling back to fn.derefNames
// only for names it finds there — recordDeref alone (which only touches
// derefNames/derefFields/derefFlags) leaves a candidate invisible to that
// walk entirely unless it's ALSO in fn.access, same as the bottom-of-
// callback update below does for every directly-visited identifier.
function recordCandidates(candidates, field, p, mode) {
for (const cand of candidates) {
recordDeref(cand, field, p, mode);
const cur = access.get(cand) || { r: false, w: false };
if (mode.includes('r')) cur.r = true;
if (mode.includes('w')) cur.w = true;
access.set(cand, cur);
}
}
if (body) {
walkTree(body, n => {
if (n.type === 'call_expression') {
const target = resolveCallTarget(n.childForFieldName('function'));
if (target && target.kind === 'direct') {
calls.add(target.name);
if (NVIC_ARM_RE.test(target.name)) {
const args = n.childForFieldName('arguments');
const first = args ? args.namedChildren[0] : null;
if (first && first.type === 'identifier') armCalls.add(first.text);
}
} else if (target && target.kind === 'indirect') {
indirectCalls.add(target.key);
}
return;
}
// Every `->` access, resolved through the SAME general chain
// (resolveSymbolicRef) regardless of whether its base is a bare
// peripheral name, a config-table array field, a helper-function
// call, or a local variable holding any of the above — see that
// function's own doc comment. Does NOT `return` afterward: walkTree
// still descends into this field_expression's own children below
// (the base expression's own identifiers, any nested `[index]`
// subscripts, ...), each getting its ordinary access-tracking the
// same as in any other expression.
if (n.type === 'field_expression' && n.childForFieldName('operator')?.text === '->') {
const candidates = resolveSymbolicRef(n.childForFieldName('argument'), scope);
if (candidates.size) recordCandidates(candidates, n.childForFieldName('field')?.text, n, classifyAccess(n));
}
if (n.type !== 'identifier') return;
const p = n.parent;
if (p && p.type === 'call_expression' && sameNode(p.childForFieldName('function'), n)) return;
if (p && p.type === 'field_expression' && sameNode(p.childForFieldName('field'), n)) return;
// skip the *declared name* itself, but not initializer values / array sizes
if (p && (p.type.endsWith('_declarator')) && sameNode(p.childForFieldName('declarator'), n)) return;
const name = resolveMacroName(n.text);
if (locals.has(name)) return;
const mode = classifyAccess(n);
const cur = access.get(name) || { r: false, w: false };
if (mode.includes('r')) cur.r = true;
if (mode.includes('w')) cur.w = true;
access.set(name, cur);
});
}
const typeNode = funcNode.childForFieldName('type');
const signature = `${typeNode ? typeNode.text + ' ' : ''}${declarator ? declarator.text : ''}`
.replace(/\s+/g, ' ');
// Names directly called inside this function's own top-level infinite loop
// (while(1)/for(;;) sitting as a direct statement of the body — not one
// nested inside some other loop/helper). Used to tell apart "runs once at
// boot" setup calls (main's clock/GPIO/peripheral init, all made *before*
// this loop) from what actually recurs at runtime — see cyclicFuncKeys in
// buildLevel0Diagram. Anywhere other than an entry point's own body this is
// vestigial (a plain function's while loop doesn't make its own callees
// "the runtime loop" — only entries seed cyclic-ness), but detecting it
// unconditionally here is simpler than special-casing "is this main".
const loopCallNames = new Set();
const loopNode = findTopLevelInfiniteLoop(body);
if (loopNode) {
walkTree(loopNode, n => {
if (n.type !== 'call_expression') return;
const fn = n.childForFieldName('function');
if (fn && fn.type === 'identifier') loopCallNames.add(fn.text);
});
}
// hasLoop is distinct from "loopCallNames is non-empty": a real for(;;)/
// while(1) whose body is just `__WFI();`/similar (sleep-until-interrupt,
// nothing internal to call) still means "we found the actual runtime loop,
// it just calls nothing worth tracking" — buildLevel0Diagram's cyclic seed
// must trust that (seed with the empty set) rather than falling back to the
// whole call tree, which is reserved for when no loop was found *at all*.
const hasLoop = !!loopNode;
return { calls, indirectCalls, armCalls, derefNames, derefFields, derefFlags, derefAddrRefs, access, signature, loopCallNames, hasLoop };
}
// Simple object-like `#define NAME OTHER_IDENT` peripheral/var aliases (e.g.
// STM32 code that names a UART's GPIO port `#define UART1_Prt GPIOB` because
// that's where its pins live) resolve to the SAME hardware block as whatever
// `OTHER_IDENT` itself resolves to — but this analyzer has no C preprocessor
// pass at all, so `UART1_Prt->CRL` and `GPIOB->CRL` used to name two
// different peripherals purely because they're spelled differently at the
// access site. Fixed with a light, best-effort pre-pass: collect every
// `#define NAME VALUE` project-wide where VALUE is *exactly* one bare
// identifier (never a function-like macro, never `((T*)0x...)` address
// casts — those define the REAL peripheral, not an alias of one, and must
// stay as themselves), then canonicalize through the chain at the same two
// points every periph/var base name is first read out of the AST
// (resolveAddrExpr below, and analyzeFunction's own `name` extraction) —
// every downstream consumer sees only the canonical name from there on.
// Module-level: rebuilt fresh at the top of every project scan from that
// scan's own files, read from deep inside analyzeFunction/resolveAddrExpr
// without threading a parameter through their whole call chain.
let MACRO_ALIASES = new Map();
const resolveMacroName = (name) => MACRO_ALIASES.get(name) || name;
// One file's `#define`s, raw (unchained) — walks the whole tree, not just
// top-level, so aliases guarded by `#ifdef` are still picked up (no macro
// is actually evaluated, so which #ifdef branch a define lives in is never
// checked — same best-effort trade-off already made for periph/DMA
// resolution elsewhere here).
function collectMacroAliases(root, out) {
walkTree(root, (n) => {
if (n.type !== 'preproc_def') return;
const name = n.childForFieldName('name')?.text;
const value = n.childForFieldName('value')?.text?.trim();
if (name && value && /^[A-Za-z_]\w*$/.test(value)) out.set(name, value);
});
}
// Chases each raw alias to whatever it ultimately names — `#define A B` +
// `#define B GPIOC` resolves `A` straight to `GPIOC`, not just one hop to
// `B`. Cycle-guarded (a chain that loops back on itself falls back to the
// last name seen before the repeat, rather than hanging).
function resolveMacroChains(raw) {
const out = new Map();
for (const start of raw.keys()) {
const seen = new Set();
let cur = start;
while (raw.has(cur) && !seen.has(cur)) { seen.add(cur); cur = raw.get(cur); }
if (cur !== start) out.set(start, cur);
}
return out;
}
// Config-table-driven peripheral access: `const PinConfig OUTPUT_PINS[N] =
// { {GPIOB, 0}, ... }; OUTPUT_PINS[i].port->BSRR = bit;` touches a real GPIO
// peripheral, but `->`'s own base here is `OUTPUT_PINS[i].port` — a whole
// subscript+field chain, not the bare identifier every other periph/var
// access in this analyzer requires — so it fell through completely
// unrecognized, silently missing from the diagram. `i` is a runtime index,
// so which exact element a given call touches can't be known statically;
// this resolves the field to the UNION of every literal SHOUTING_SNAKE_CASE
// value ever assigned to it across the array's own initializer instead —
// "touches ANY of these", not a precise per-call answer (explicitly
// accepted trade-off — the alternative is the access not appearing at all).
// ARRAY_FIELD_PERIPHS: arrayName -> Map(fieldName -> Set(candidate names));
// rebuilt fresh per project scan, same as MACRO_ALIASES right above.
let ARRAY_FIELD_PERIPHS = new Map();
// Same idea, one level simpler: a FLAT array (no struct/field involved) —
// `static GPIO_TypeDef *const PORTS[] = { GPIOA, GPIOB };` — where `arr[i]`
// alone (no trailing `.field`) names one of its own literal elements.
// arrayName -> Set(candidate names).
let ARRAY_ELEMENT_PERIPHS = new Map();
// A struct field's own declarator name — `GPIO_TypeDef *port;` wraps its
// `field_identifier` in a pointer_declarator, so this unwraps one layer the
// same way findNameInDeclarator does for ordinary variable declarators
// (which never see a field_identifier, hence its own separate helper here).
function fieldIdentifierName(declarator) {
let d = declarator;
while (d) {
if (d.type === 'field_identifier') return d.text;
d = d.childForFieldName('declarator');
}
return null;
}
// Struct field order (`typedef struct { A; B; } Name;` -> ['a','b']),
// needed to match a POSITIONAL array-of-struct initializer element
// (`{ GPIOA, 9 }`, no `.port =`/`.pin =` designators) back to field names.
function collectStructFieldOrders(root, out) {
walkTree(root, (n) => {
if (n.type !== 'type_definition') return;
const typeNode = n.childForFieldName('type');
const nameNode = n.childForFieldName('declarator');
if (!typeNode || typeNode.type !== 'struct_specifier' || !nameNode) return;
const body = typeNode.childForFieldName('body');
if (!body) return;
const fields = [];
for (const fd of body.namedChildren) {
if (fd.type !== 'field_declaration') continue;
for (const d of childrenForField(fd, 'declarator')) {
const fname = fieldIdentifierName(d);
if (fname) fields.push(fname);
}
}
if (fields.length) out.set(nameNode.text, fields);
});
}
// One file's global array-of-known-struct declarations, each field's
// literal values collected into ARRAY_FIELD_PERIPHS (see its own doc
// comment above) whenever they look like SHOUTING_SNAKE_CASE peripheral
// names — every other kind of field value (numbers, expressions) is simply
// never added, so a field like `.pin` (plain integers) never produces a
// (harmless, just unused) entry at all.
function collectArrayFieldPeripherals(root, structFields, out) {
walkTree(root, (n) => {
if (n.type !== 'declaration' || insideFunction(n)) return;
const typeNode = n.childForFieldName('type');
const fieldOrder = typeNode && structFields.get(typeNode.text);
if (!fieldOrder) return;
for (const d of childrenForField(n, 'declarator')) {
if (d.type !== 'init_declarator') continue;
const arrDecl = d.childForFieldName('declarator');
if (!arrDecl || arrDecl.type !== 'array_declarator') continue;
const arrName = findNameInDeclarator(arrDecl);
const initList = d.childForFieldName('value');
if (!arrName || !initList || initList.type !== 'initializer_list') continue;
let fieldMap = out.get(arrName);
if (!fieldMap) { fieldMap = new Map(); out.set(arrName, fieldMap); }
for (const elem of initList.namedChildren) {
// each element is either `[IDX] = {...}` (initializer_pair) or a
// bare `{...}` (plain positional array literal) — either way, what
// we actually want is the {...} itself.
const elemInit = elem.type === 'initializer_pair' ? elem.childForFieldName('value') : elem;
if (!elemInit || elemInit.type !== 'initializer_list') continue;
let pos = 0;
for (const item of elemInit.namedChildren) {
let fieldName, valueNode;
if (item.type === 'initializer_pair') {
const desig = item.childForFieldName('designator');
const fid = desig && desig.type === 'field_designator' ? desig.namedChildren[0] : null;
fieldName = fid && fid.text;
valueNode = item.childForFieldName('value');
} else {
fieldName = fieldOrder[pos];
valueNode = item;
pos++;
}
if (!fieldName || !valueNode) continue;
if (valueNode.type === 'identifier' && MACRO_CONST_RE.test(valueNode.text)) {
if (!fieldMap.has(fieldName)) fieldMap.set(fieldName, new Set());
fieldMap.get(fieldName).add(valueNode.text);
}
}
}
}
});
}
// Flat (no struct) global array literal — `T *const PORTS[] = { GPIOA,
// GPIOB };` — feeds ARRAY_ELEMENT_PERIPHS (see its own doc comment). The
// declarator can be wrapped in an extra pointer_declarator ahead of the
// array_declarator (`T *const NAME[]` — the `*const` itself, not the array)
// so this unwraps however many layers separate the two, unlike
// collectArrayFieldPeripherals's array (always the OUTERMOST declarator
// there, since a struct-typed array is never itself behind a pointer).
function collectArrayElementPeripherals(root, out) {
walkTree(root, (n) => {
if (n.type !== 'declaration' || insideFunction(n)) return;
for (const d of childrenForField(n, 'declarator')) {
if (d.type !== 'init_declarator') continue;
let ad = d.childForFieldName('declarator');
while (ad && ad.type !== 'array_declarator') ad = ad.childForFieldName && ad.childForFieldName('declarator');
if (!ad || ad.type !== 'array_declarator') continue;
const arrName = findNameInDeclarator(d);
const initList = d.childForFieldName('value');
if (!arrName || !initList || initList.type !== 'initializer_list' || !initList.namedChildren.length) continue;
const items = initList.namedChildren;
if (!items.every((it) => it.type === 'identifier' && MACRO_CONST_RE.test(it.text))) continue;
out.set(arrName, new Set(items.map((it) => it.text)));
}
});
}
// General symbolic-reference resolver — "which peripheral(s) could this
// expression evaluate to", by walking the SAME handful of primitives every
// indirection idiom seen so far turned out to be built from: a bare name
// (always its own answer, unless a known LOCAL resolution overrides it —
// the historical base case: any non-local identifier used as `->`'s base is
// assumed to name a peripheral, CMSIS's `((T*)BASE_ADDR)` convention, no
// naming-convention filter), a struct-array field's own static initializer
// (ARRAY_FIELD_PERIPHS), a flat array's own elements (ARRAY_ELEMENT_PERIPHS
// or the CALLER's own locally-declared array, via `scope.localArrays`), or
// a function call resolved through its own precomputed return-expression
// summary (FUNC_RETURN_PERIPHS) — chased recursively instead of hand-
// matching each shape's own exact AST pattern at its own call site. Always
// returns a Set (possibly empty — "no candidates" for anything genuinely
// computed, e.g. real pointer arithmetic, or a plain unresolved local,
// rather than a wrong guess).
// scope: { locals: Set(names) — this function's OWN local variables, never
// themselves a project-wide peripheral unless localVars below says so;
// localArrays: Map(name -> Set) — arrays declared INSIDE this function;
// localVars: Map(name -> Set) — locals already resolved via this same
// function, one assignment at a time, in declaration order (see
// analyzeFunction) }. Omit entirely (undefined) when resolving outside
// any function context (a global initializer, or a callee's own
// return-summary computation using only ITS OWN locals).
function resolveSymbolicRef(node, scope) {
let n = node;
for (;;) {
if (n && n.type === 'parenthesized_expression') { n = n.namedChildren[0]; continue; }
if (n && n.type === 'cast_expression') { n = n.childForFieldName('value'); continue; }
break;
}
if (!n) return new Set();
if (n.type === 'identifier') {
const name = resolveMacroName(n.text);
if (scope && scope.localVars && scope.localVars.has(name)) return scope.localVars.get(name);
if (scope && scope.locals && scope.locals.has(name)) return new Set(); // genuine unresolved local, never a global periph guess
return new Set([name]);
}
if (n.type === 'field_expression') {
if (n.childForFieldName('operator')?.text !== '.') return new Set();
let base = n.childForFieldName('argument');
while (base && base.type === 'parenthesized_expression') base = base.namedChildren[0];
if (!base || base.type !== 'subscript_expression') return new Set();
let arrBase = base.childForFieldName('argument');
while (arrBase && arrBase.type === 'parenthesized_expression') arrBase = arrBase.namedChildren[0];
if (!arrBase || arrBase.type !== 'identifier') return new Set();
const field = n.childForFieldName('field')?.text;
const fieldMap = ARRAY_FIELD_PERIPHS.get(arrBase.text);
return (field && fieldMap && fieldMap.get(field)) || new Set();
}
if (n.type === 'subscript_expression') {
let arrBase = n.childForFieldName('argument');
while (arrBase && arrBase.type === 'parenthesized_expression') arrBase = arrBase.namedChildren[0];
if (!arrBase || arrBase.type !== 'identifier') return new Set();
return (scope && scope.localArrays && scope.localArrays.get(arrBase.text))
|| ARRAY_ELEMENT_PERIPHS.get(arrBase.text) || new Set();
}
if (n.type === 'call_expression') {
const fnNode = n.childForFieldName('function');
if (!fnNode || fnNode.type !== 'identifier') return new Set();
return FUNC_RETURN_PERIPHS.get(fnNode.text) || new Set();
}
return new Set();
}
// A function's own local array literals (`T *const PORTS[] = {...};`
// declared INSIDE it) — the scaffolding resolveSymbolicRef needs to resolve
// a RETURN statement built on one, WITHOUT yet having that function's own
// full analyzeFunction scope (this runs in the project-wide pre-pass,
// before any function body is otherwise analyzed).
function collectLocalArrayLiterals(body) {
const out = new Map();
walkTree(body, (n) => {
if (n.type !== 'declaration') return;
for (const d of childrenForField(n, 'declarator')) {
if (d.type !== 'init_declarator') continue;
const nm = findNameInDeclarator(d);
const value = d.childForFieldName('value');
if (!nm || !value || value.type !== 'initializer_list' || !value.namedChildren.length) continue;
const items = value.namedChildren;
if (!items.every((it) => it.type === 'identifier' && MACRO_CONST_RE.test(it.text))) continue;
out.set(nm, new Set(items.map((it) => it.text)));
}
});
return out;
}
// A "peripheral-resolving helper" — one more hop of indirection past
// ARRAY_FIELD_PERIPHS/ARRAY_ELEMENT_PERIPHS: `static inline GPIO_TypeDef
// *port_reg(uint8_t port) { static GPIO_TypeDef *const PORTS[] = { GPIOA,
// GPIOB }; return PORTS[port]; }` wraps a PortId enum around the same
// "which peripheral" question those tables only used to answer directly.
// `port_reg(OUTPUT_PINS[i].port)->BSRR` (or the equivalent through a local
// — see analyzeFunction's own localPeriphVars) needs this resolved too.
// Driven by resolveSymbolicRef — not limited to the exact `return ARR[x];`
// shape, since anything that resolver can already chase (a direct `return
// GPIOA;`, `return ARR[x].field;`, even a call to ANOTHER such helper)
// resolves through the same recursive machinery. funcName -> Set(candidate
// names).
let FUNC_RETURN_PERIPHS = new Map();
function collectFuncReturnPeripherals(funcs, out) {
for (const fn of funcs) {
const body = fn.node.childForFieldName('body');
if (!body) continue;
const localArrays = collectLocalArrayLiterals(body);
if (!localArrays.size) continue;
const scope = { locals: new Set(), localArrays, localVars: new Map() };
let found = null;
walkTree(body, (n) => {
if (found || n.type !== 'return_statement') return;
const val = n.namedChildren[0];
if (!val) return;
const resolved = resolveSymbolicRef(val, scope);
if (resolved.size) found = resolved;
});
if (found) out.set(fn.name, found);
}
}
// Strips a DMA CPAR/CMAR assignment's right-hand side (or a local pointer's
// own initializer — see resolveLocalAlias) down to the expression that
// actually names the source/destination address — casts (`(uint32_t)...`)
// and parens first, then, if what's left is `&something`, unwraps that one
// layer too (both `X->CPAR = (uint32_t)&USART1->DR` and
// `X->CPAR = &USART1->DR` name the same target either way; a plain
// `X->CMAR = u1_rx_buf` never had a `&` in the first place — arrays decay to
// a pointer on their own), then unwraps one `[index]` layer the same way
// (`&u1_q[u1_q_tail]` names the array `u1_q`, whichever slot). What remains
// is classified: a field access (`->` or `.`) names whatever it's rooted at
// (`field` is kept too, for the hover-detail label — see dotDmaFlowEdge),
// unwrapping any `[index]` layers on *that* base too (`bufs[i].payload`
// names `bufs`, same as the top-level `&arr[i]` case) — and a bare
// identifier names a var. Neither branch yet knows whether its base name is
// itself a global or a local pointer/array (e.g. `m` in `m->data`, off a
// local `U1Msg *m = &u1_q[...]`); the caller resolves that ambiguity via
// resolveLocalAlias, since only it has the enclosing function's
// `locals`/`localAliases`. `->` vs `.` picks the default guess for "what
// kind of global is this, assuming it isn't local": arrow-on-a-global is
// (almost) always a real MCU peripheral register block (CMSIS's
// `((T*)BASE_ADDR)` pattern) — dot-on-a-global is the opposite, ordinary
// field access on a plain global struct/array, never a peripheral.
function resolveAddrExpr(node) {
let n = node;
for (;;) {
if (n && n.type === 'parenthesized_expression') { n = n.namedChildren[0]; continue; }
if (n && n.type === 'cast_expression') { n = n.childForFieldName('value'); continue; }
break;
}
if (!n) return null;
if (n.type === 'pointer_expression' && n.childForFieldName('operator')?.text === '&') {
n = n.childForFieldName('argument');
while (n && n.type === 'parenthesized_expression') n = n.namedChildren[0];
}
if (!n) return null;
if (n.type === 'subscript_expression') {
n = n.childForFieldName('argument');
while (n && n.type === 'parenthesized_expression') n = n.namedChildren[0];
}
if (!n) return null;
if (n.type === 'field_expression') {
const op = n.childForFieldName('operator')?.text;
if (op === '->' || op === '.') {
let base = n.childForFieldName('argument');
while (base && base.type === 'subscript_expression') base = base.childForFieldName('argument');
while (base && base.type === 'parenthesized_expression') base = base.namedChildren[0];
if (!base || base.type !== 'identifier') return null;
const field = n.childForFieldName('field')?.text;
const baseName = resolveMacroName(base.text);
return op === '->' ? { kind: 'periph', name: baseName, field } : { kind: 'var', name: baseName, field };
}
}
if (n.type === 'identifier') return { kind: 'var', name: resolveMacroName(n.text) };
return null;
}
// Follows resolveAddrExpr's result one step further when it turns out to
// name a local, not a real global/peripheral — `m->data` off
// `U1Msg *m = &u1_q[u1_q_tail];` first resolves (structurally) to
// {kind:'periph', name:'m', field:'data'}, since resolveAddrExpr alone can't
// tell a peripheral register block apart from a local struct pointer by AST
// shape; `m` being in `locals` is exactly that tell. localAliases (built once