All files / shared io-registry-parser.ts

94.57% Statements 418/442
83.26% Branches 214/257
96% Functions 72/75
98.37% Lines 363/369

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114                                                                                    44x           44x             44x 44x 44x 44x 44x 44x 44x                                                                                                                                                       442x 442x       442x 8x 8x 8x 8x         442x 19x 19x 19x 19x         442x 335x 302x 302x 302x 302x       442x               781x 172x 172x 71x 71x   101x                     442x   442x 30x   92x 89x 27x     442x                       286x   286x 286x 6x 6x 6x 4x 4x   2x   280x 280x                                                 48x 48x 48x   48x 48x 48x 480x 445x 445x   48x             48x   136x   213x       131x                     23x 23x 1039x 1015x 23x 23x     1x                 35x 23x 46x 23x   12x 12x                     512x     512x 1024x 1024x     49x 49x 49x 49x 49x   48x 48x   35x 35x 49x   49x                     512x                                             74x 74x     74x       74x   74x 74x       74x 74x 74x   74x                                 7x 2x   5x 3x 3x   2x 2x                             21x 112x 112x                                           22x 22x   18x 92x 92x 92x                     18x                               473x 473x 473x 222x 222x 222x                 251x                                                           330x 330x 1x         1x       329x   63x 43x 22x 22x       329x 43x 43x 22x                 22x 4x             22x   21x 21x       286x 286x 17x           17x     269x                           74x 56x 54x 56x 56x   74x 5x   74x 37x   74x 10x   74x 1x                             74x 54x 56x 56x 54x   54x 54x 54x     74x 74x 53x                     54x   11x   40x   3x                                   74x   74x                 74x       74x           74x 7x 7x               74x 74x   74x         442x 442x 442x 442x   442x 442x                   442x 260x 260x 260x 260x 260x   260x                     442x 442x 408x 408x 149x   259x       442x 442x 442x 329x   442x         40x   40x 109x 109x 109x 109x 109x   74x                   74x       42x                                 32x     44x 44x 44x 44x                               26741x 26074x 26741x       14489x 2775x 14489x       289x 289x 289x       3386x 2719x 11781x 2719x       1953x 7580x 1953x       2x 1x               1286x 1286x   1286x 1286x 7x 7x 7x 7x 7x   1286x   139x 139x 139x 139x 139x             1286x 1286x   139x 139x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x   2x                 760x 760x 760x 1953x 1953x 1286x 1286x 1286x   760x                   760x 760x 2280x   2280x 29x 28x 28x 28x 28x         760x 2x 2x   3x 3x 2x                         70x 65x 65x 65x   70x 5x 5x 5x             116x 116x 116x 116x 116x 116x 116x   116x 690x 690x         690x   690x 70x 70x 70x 70x 70x 70x     70x 70x   70x               70x                 690x 690x     116x 116x 65x 65x 44x   116x 44x 9x 116x 22x   116x                           116x             35x 45x   9x             8x 8x 8x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x   8x    
/**
 * io-registry-parser.ts
 *
 * Pure static parser for the Hybrid IO-Registry.
 * Analyses Arduino/C++ source code and returns IOPinRecord[] for the
 * 20 known hardware pins (0-13 digital, 14-19 = A0-A5 analog).
 *
 * Covers all 11 SSOT test cases:
 *   TC1  – literal pin + literal mode
 *   TC2  – A0-A5 alias resolution
 *   TC3  – for-loop expansion (variable range)
 *   TC4  – const int / variable resolution
 *   TC5  – #define resolution
 *   TC6  – static entry is created once (no per-call duplication)
 *   TC7  – same pin used in read AND write → both columns filled
 *   TC8  – dynamic pin (runtime() etc.) → NOT included (runtime only)
 *   TC9  – conflict: INPUT/INPUT_PULLUP mode + digitalWrite → warning
 *   TC10 – array index resolution (pins[1])
 *   TC11 – multiple different pinMode modes → warning + both lines
 */
 
import type { IOPinRecord } from "./schema";
import type { PinMode } from "@shared/types/arduino.types";
import {
  resolveSourceProject,
  type ResolvedSourceProject,
  type SourceLocation,
  type SourceProject,
  type SourceProjectDiagnostic,
} from "@shared/source-project";
import {
  FOR_LOOP_TYPED,
  FOR_LOOP_BARE,
  stripComments,
  lineAt,
} from "@shared/parser-patterns";
 
// ─────────────────────────────────────────────────────────────────────────────
// Constants
// ─────────────────────────────────────────────────────────────────────────────
 
/** Built-in Arduino pin-name constants mapped to numeric IDs (0-19). */
const BUILTIN_CONSTANTS: Record<string, number> = {
  LED_BUILTIN: 13,
  A0: 14, A1: 15, A2: 16, A3: 17, A4: 18, A5: 19,
};
 
/** Canonical mode name table. */
const MODE_MAP: Record<string, PinMode> = {
  INPUT: "INPUT",       "0": "INPUT",
  OUTPUT: "OUTPUT",     "1": "OUTPUT",
  INPUT_PULLUP: "INPUT_PULLUP", "2": "INPUT_PULLUP",
};
 
// Regex patterns for symbol resolution (S6353: use \w instead of [A-Za-z0-9_])
const DEFINE_PATTERN = /^#define\s+([A-Za-z_]\w*)\s+(\w+)/gm;
const CONST_PATTERN = /\bconst\s+(?:int|byte|uint8_t|uint16_t|short|long)\s+([A-Za-z_]\w*)\s*=\s*(\w+)\s*;/g;
const VAR_PATTERN = /\b(?:int|byte|uint8_t)\s+([A-Za-z_]\w*)\s*=\s*(\w+)\s*;/g;
const ARRAY_PATTERN = /\b(?:const\s+)?(?:int|byte|uint8_t)\s+([A-Za-z_]\w*)\s*\[\s*(?:\d+|[A-Za-z_]\w*)?\s*\]\s*=\s*\{([^}]+)\}/g; // NOSONAR S5843
const FOR_BRACE_TAIL_RE = /^ *(\{)?/;
const ARRAY_ACCESS_PATTERN = /^([A-Za-z_]\w*)\s*\[\s*(\d+|[A-Za-z_]\w*)\s*\]$/;
const FUNCTION_CALL_PATTERN = /\b(pinMode|digitalRead|digitalWrite|analogRead|analogWrite)\s*\(\s*(\w+(?:\[\w+\])?)(?:\s*,\s*(\w+))?/g;
 
export type StaticIOOperation =
  | "pinMode"
  | "digitalRead"
  | "digitalWrite"
  | "analogRead"
  | "analogWrite";
 
export interface StaticIOCall {
  op: StaticIOOperation;
  pinId: number;
  line: number;
  /** Present for project analysis; omitted by the legacy string API. */
  file?: string;
  /** Stable order in the expanded source, used instead of comparing file lines. */
  sourceOrder?: number;
  sourceExpression: string;
  mode?: PinMode;
  loopBody?: "braced" | "braceless";
}
 
/** An I/O call whose pin expression cannot be resolved without executing it. */
export interface UnresolvedStaticIOCall {
  op: StaticIOOperation;
  line: number;
  file?: string;
  sourceOrder?: number;
  sourceExpression: string;
  mode?: PinMode;
}
 
/** Canonical statically-resolved I/O facts for one Arduino pin. */
export interface StaticIOPinAnalysis {
  pinId: number;
  calls: StaticIOCall[];
}
 
/**
 * Canonical result of the best-effort static I/O analysis.
 *
 * Only unambiguously resolved pins are included. Dynamic or unsupported
 * expressions remain the responsibility of the runtime registry.
 */
export interface StaticIOAnalysis {
  pins: StaticIOPinAnalysis[];
  unresolvedCalls: UnresolvedStaticIOCall[];
  symbols: Record<string, number>;
}
 
export interface StaticIOProjectAnalysis extends StaticIOAnalysis {
  diagnostics: readonly SourceProjectDiagnostic[];
  complete: boolean;
  resolved: ResolvedSourceProject;
}
 
export interface StaticIOProjectPinRecord extends IOPinRecord {
  pinModeLocations?: SourceLocation[];
  digitalReadLocations?: SourceLocation[];
  digitalWriteLocations?: SourceLocation[];
  analogReadLocations?: SourceLocation[];
  analogWriteLocations?: SourceLocation[];
}
 
// ─────────────────────────────────────────────────────────────────────────────
// Symbol resolution
// ─────────────────────────────────────────────────────────────────────────────
 
/**
 * Build symbol table: name → pin ID (0-19).
 * Handles: built-in constants, #define, const int/byte, plain int/byte.
 */
function buildSymbols(clean: string): {
  values: Map<string, number>;
  userSymbols: Set<string>;
} {
  const syms = new Map<string, number>(Object.entries(BUILTIN_CONSTANTS));
  const userSymbols = new Set<string>();
 
  // #define NAME VALUE
  let m: RegExpExecArray | null;
  while ((m = DEFINE_PATTERN.exec(clean)) !== null) {
    const v = resolveToken(m[2], syms);
    Eif (v !== undefined) {
      syms.set(m[1], v);
      userSymbols.add(m[1]);
    }
  }
 
  // const int/byte NAME = VALUE;
  while ((m = CONST_PATTERN.exec(clean)) !== null) {
    const v = resolveToken(m[2], syms);
    Eif (v !== undefined) {
      syms.set(m[1], v);
      userSymbols.add(m[1]);
    }
  }
 
  // plain int/byte NAME = VALUE; (common in Arduino, e.g. int led = 12;)
  while ((m = VAR_PATTERN.exec(clean)) !== null) {
    if (syms.has(m[1])) continue; // already set by const variant
    const v = resolveToken(m[2], syms);
    Eif (v !== undefined) {
      syms.set(m[1], v);
      userSymbols.add(m[1]);
    }
  }
 
  return { values: syms, userSymbols };
}
 
/** Resolve a single token (numeric literal, A0-A5, or symbol) to a pin ID. */
function resolveToken(
  token: string,
  syms: Map<string, number>,
): number | undefined {
  if (/^\d+$/.test(token)) return Number.parseInt(token, 10);
  const analogMatch = /^A(\d+)$/.exec(token);
  if (analogMatch) {
    const n = Number.parseInt(analogMatch[1], 10);
    return n >= 0 && n <= 5 ? 14 + n : undefined;
  }
  return syms.get(token);
}
 
/**
 * Build array table: `int arr[] = {a, b, c}` → arr → [pinId, pinId, …].
 * Used to resolve array-index pin expressions like `pins[1]`.
 */
function buildArrays(
  clean: string,
  syms: Map<string, number>,
): Map<string, number[]> {
  const arrays = new Map<string, number[]>();
  let m: RegExpExecArray | null;
  while ((m = ARRAY_PATTERN.exec(clean)) !== null) {
    const vals = m[2]
      .split(",")
      .map((v) => resolveToken(v.trim(), syms));
    if (vals.every((v): v is number => v !== undefined)) {
      arrays.set(m[1], vals);
    }
  }
  return arrays;
}
 
/**
 * Resolve a pin expression (literal, symbol, or array-index) to a pin ID 0-19.
 * Returns undefined if the expression is not statically resolvable (→ TC 8).
 */
function resolvePin(
  expr: string,
  syms: Map<string, number>,
  arrays: Map<string, number[]>,
): number | undefined {
  const t = expr.trim();
  // Array access: name[index]
  const arrM = ARRAY_ACCESS_PATTERN.exec(t);
  if (arrM) {
    const arr = arrays.get(arrM[1]);
    const idx = Number.parseInt(arrM[2], 10);
    if (arr && idx < arr.length) {
      const id = arr[idx];
      return id >= 0 && id <= 19 ? id : undefined;
    }
    return undefined;
  }
  const n = resolveToken(t, syms);
  return n !== undefined && n >= 0 && n <= 19 ? n : undefined;
}
 
// ─────────────────────────────────────────────────────────────────────────────
// For-loop range detection
// ─────────────────────────────────────────────────────────────────────────────
 
interface LoopRange {
  startPos: number;
  endPos: number;
  startLine: number;
  variable: string;
  values: number[];
  hasBrace: boolean;
}
 
/**
 * Generate loop values based on operator and limits.
 * Uses data-driven approach to reduce cognitive complexity.
 */
function generateLoopValues(
  start: number,
  op: string,
  limitVal: number,
): number[] {
  const values: number[] = [];
  const compareFunc = getComparisonFunction(op);
  Iif (!compareFunc) return values;
 
  const direction = op === ">" || op === ">=" ? -1 : 1;
  let i = start;
  while (values.length <= 20) {
    if (!compareFunc(i, limitVal)) break;
    values.push(i);
    i += direction;
  }
  return values;
}
 
/**
 * Get comparison function for a given operator string.
 */
function getComparisonFunction(op: string): ((a: number, b: number) => boolean) | null {
  switch (op) {
    case "<":
      return (a, b) => a < b;
    case "<=":
      return (a, b) => a <= b;
    case ">":
      return (a, b) => a > b;
    case ">=":
      return (a, b) => a >= b;
    default:
      return null;
  }
}
 
/**
 * Find matching closing brace in a string starting from a given position.
 * Helper to reduce cognitive complexity in findLoopRanges.
 */
function findMatchingBrace(str: string, openPos: number): number {
  let depth = 0;
  for (let i = openPos; i < str.length; i++) {
    if (str[i] === "{") depth++;
    else if (str[i] === "}") {
      depth--;
      if (depth === 0) return i;
    }
  }
  return str.length;
}
 
/** Find the end position of a for-loop body (braced or braceless). */
function findLoopBodyEnd(
  clean: string,
  headerEnd: number,
  hasBrace: boolean,
): number {
  if (hasBrace) {
    let openBrace = headerEnd - 1;
    while (openBrace < clean.length && clean[openBrace] !== "{") openBrace++;
    return findMatchingBrace(clean, openBrace);
  }
  const semiPos = clean.indexOf(";", headerEnd);
  return semiPos >= 0 ? semiPos : clean.length;
}
 
/**
 * Find all for-loops with a numeric iteration variable over a statically
 * determinable range, e.g. `for (int i = 2; i < 4; i++)`.
 */
function findLoopRanges(
  clean: string,
  syms: Map<string, number>,
): LoopRange[] {
  const ranges: LoopRange[] = [];
  let m: RegExpExecArray | null;
 
  for (const forRe of [FOR_LOOP_TYPED, FOR_LOOP_BARE]) {
    forRe.lastIndex = 0;
    while ((m = forRe.exec(clean)) !== null) {
      // FOR_LOOP_TYPED: groups are [full, type, var, start, op, limit]
      // FOR_LOOP_BARE: groups are [full, empty, var, start, op, limit]
      const variable = m[2];
      const start = Number.parseInt(m[3], 10);
      const op = m[4];
      const limitVal = resolveToken(m[5], syms) ?? Number.parseInt(m[5], 10);
      if (Number.isNaN(limitVal)) continue;
 
      const values = generateLoopValues(start, op, limitVal);
      if (values.length === 0 || values.length > 20) continue;
 
      const tail = clean.slice(m.index + m[0].length);
      const hasBrace = !!FOR_BRACE_TAIL_RE.exec(tail)?.[1];
      const endPos = findLoopBodyEnd(clean, m.index + m[0].length, hasBrace);
 
      ranges.push({
        startPos: m.index,
        endPos,
        startLine: lineAt(clean, m.index),
        variable,
        values,
        hasBrace,
      });
    }
  }
 
  return ranges;
}
 
// ─────────────────────────────────────────────────────────────────────────────
// Main exported function
// ─────────────────────────────────────────────────────────────────────────────
 
/**
 * Detect conflicts in pin mode and operation assignments.
 * Returns { pinModeConflict, operationConflict, outputReadConflict, hasInputMode, hasOutputMode }
 */
function detectPinConflicts(
  pmCalls: StaticIOCall[],
  drCalls: StaticIOCall[],
  dwCalls: StaticIOCall[],
  arCalls: StaticIOCall[],
  awCalls: StaticIOCall[],
): {
  pinModeConflict: boolean;
  operationConflict: boolean;
  outputReadConflict: boolean;
  uniqueModes: PinMode[];
} {
  const allModes = pmCalls.map((c) => c.mode);
  const uniqueModes = [...new Set(allModes)] as PinMode[];
 
  // TC 11: same pin configured with multiple DIFFERENT modes
  const pinModeConflict = uniqueModes.length > 1;
 
  // TC 9: pin set to INPUT/INPUT_PULLUP AND written via digital/analogWrite
  const hasInputMode =
    pmCalls.length > 0 &&
    (uniqueModes.includes("INPUT") || uniqueModes.includes("INPUT_PULLUP"));
  const hasWrite = dwCalls.length > 0 || awCalls.length > 0;
  const operationConflict = hasInputMode && hasWrite;
 
  // TC 9b: pin set to OUTPUT AND read via digital/analogRead
  const hasOutputMode =
    pmCalls.length > 0 && uniqueModes.includes("OUTPUT");
  const hasRead = drCalls.length > 0 || arCalls.length > 0;
  const outputReadConflict = hasOutputMode && hasRead;
 
  return {
    pinModeConflict,
    operationConflict,
    outputReadConflict,
    uniqueModes,
  };
}
 
/**
 * Generate conflict message based on detected conflict type.
 */
function generateConflictMessage(
  pinModeConflict: boolean,
  operationConflict: boolean,
  outputReadConflict: boolean,
  uniqueModes: PinMode[],
): string {
  if (pinModeConflict) {
    return `Multiple modes: ${[...uniqueModes].join(", ")}`;
  }
  if (operationConflict) {
    const nonOutputModes = uniqueModes.filter((mm) => mm !== "OUTPUT");
    return `Write on ${nonOutputModes.join("/")} pin`;
  }
  Eif (outputReadConflict) {
    return "Read on OUTPUT pin";
  }
  return "";
}
 
/**
 * Process an expanded for-loop variable and add entries to the list.
 */
function processLoopExpansion(
  loop: LoopRange,
  op: StaticIOOperation,
  sourceExpression: string,
  secondArg: string,
  entries: StaticIOCall[],
): void {
  for (const pinId of loop.values) {
    Iif (pinId < 0 || pinId > 19) continue;
    processStaticPin(
      pinId,
      op,
      sourceExpression,
      secondArg,
      loop.startLine,
      entries,
      loop.hasBrace ? "braced" : "braceless",
    );
  }
}
 
/** Expand an array access whose index is the active loop variable. */
function processArrayLoopExpansion(
  loop: LoopRange,
  arrayName: string,
  op: StaticIOOperation,
  sourceExpression: string,
  secondArg: string,
  arrays: Map<string, number[]>,
  entries: StaticIOCall[],
): boolean {
  const values = arrays.get(arrayName);
  if (!values) return false;
 
  for (const index of loop.values) {
    const pinId = values[index];
    Eif (pinId !== undefined) {
      processStaticPin(
        pinId,
        op,
        sourceExpression,
        secondArg,
        loop.startLine,
        entries,
        loop.hasBrace ? "braced" : "braceless",
      );
    }
  }
  return true;
}
 
/**
 * Process a statically-resolved pin and add entry to the list.
 */
function processStaticPin(
  pinId: number,
  op: StaticIOOperation,
  sourceExpression: string,
  secondArg: string,
  callLine: number,
  entries: StaticIOCall[],
  loopBody?: "braced" | "braceless",
): void {
  const resolvedPinId =
    op === "analogRead" && pinId >= 0 && pinId <= 5 ? pinId + 14 : pinId;
  const loopContext = loopBody === undefined ? {} : { loopBody };
  if (op === "pinMode") {
    const mode = MODE_MAP[secondArg];
    Iif (!mode) return;
    entries.push({
      op,
      pinId: resolvedPinId,
      line: callLine,
      sourceExpression,
      mode,
      ...loopContext,
    });
  } else {
    entries.push({
      op,
      pinId: resolvedPinId,
      line: callLine,
      sourceExpression,
      ...loopContext,
    });
  }
}
 
interface CallContext {
  loops: LoopRange[];
  syms: Map<string, number>;
  arrays: Map<string, number[]>;
  entries: StaticIOCall[];
  unresolvedCalls: UnresolvedStaticIOCall[];
}
 
/**
 * Process a single function call and add entries to the entries list.
 * Handles for-loop expansion and static pin resolution.
 */
function processCallExpression(
  op: StaticIOOperation,
  pinExpr: string,
  secondArg: string,
  callPos: number,
  callLine: number,
  ctx: CallContext,
): void {
  const { loops, syms, arrays, entries, unresolvedCalls } = ctx;
  if (op === "pinMode" && !MODE_MAP[secondArg]) {
    unresolvedCalls.push({
      op,
      line: callLine,
      sourceExpression: pinExpr,
    });
    return;
  }
 
  // ── Check for-loop variable expansion (TC 3) ──────────────────────────
  const loop = loops.find(
    (l) => {
      if (l.startPos > callPos || callPos > l.endPos) return false;
      if (l.variable === pinExpr) return true;
      const arrayAccess = ARRAY_ACCESS_PATTERN.exec(pinExpr);
      return arrayAccess?.[2] === l.variable;
    },
  );
 
  if (loop) {
    const arrayAccess = ARRAY_ACCESS_PATTERN.exec(pinExpr);
    if (arrayAccess?.[2] === loop.variable) {
      const expanded = processArrayLoopExpansion(
        loop,
        arrayAccess[1],
        op,
        pinExpr,
        secondArg,
        arrays,
        entries,
      );
      if (!expanded) {
        unresolvedCalls.push({
          op,
          line: callLine,
          sourceExpression: pinExpr,
          mode: MODE_MAP[secondArg],
        });
      }
      return;
    }
    processLoopExpansion(loop, op, pinExpr, secondArg, entries);
    return;
  }
 
  // ── Statically resolve pin expression ────────────────────────────────
  const pinId = resolvePin(pinExpr, syms, arrays);
  if (pinId === undefined) {
    unresolvedCalls.push({
      op,
      line: callLine,
      sourceExpression: pinExpr,
      mode: MODE_MAP[secondArg],
    });
    return;
  }
 
  processStaticPin(pinId, op, pinExpr, secondArg, callLine, entries);
}
 
/**
 * Populate extended-view line arrays in IOPinRecord.
 */
function populateLineArrays(
  record: IOPinRecord,
  pmCalls: StaticIOCall[],
  drCalls: StaticIOCall[],
  dwCalls: StaticIOCall[],
  arCalls: StaticIOCall[],
  awCalls: StaticIOCall[],
): void {
  if (pmCalls.length > 0) {
    record.pinModeLines = pmCalls.map((c) => c.line);
    record.pinModeModes = pmCalls
      .map((c) => c.mode)
      .filter((m): m is PinMode => m !== undefined);
  }
  if (drCalls.length > 0) {
    record.digitalReadLines = drCalls.map((c) => c.line);
  }
  if (dwCalls.length > 0) {
    record.digitalWriteLines = dwCalls.map((c) => c.line);
  }
  if (arCalls.length > 0) {
    record.analogReadLines = arCalls.map((c) => c.line);
  }
  if (awCalls.length > 0) {
    record.analogWriteLines = awCalls.map((c) => c.line);
  }
}
 
/**
 * Populate legacy fields for backward compatibility with runtime registry.
 */
function populateLegacyFields(
  record: IOPinRecord,
  pmCalls: StaticIOCall[],
  drCalls: StaticIOCall[],
  dwCalls: StaticIOCall[],
  arCalls: StaticIOCall[],
  awCalls: StaticIOCall[],
): void {
  if (pmCalls.length > 0) {
    const allModes = pmCalls
      .map((c) => c.mode)
      .filter((m): m is PinMode => m !== undefined);
    const lastMode = allModes.at(-1);
    // eslint-disable-next-line unicorn/prefer-at -- .at(-1) returns T|undefined, not narrowed by length guard
    const lastPmCall = pmCalls[pmCalls.length - 1];
    record.pinMode = convertModeToNumeric(lastMode);
    record.definedAt = { line: lastPmCall.line };
  }
 
  const nonPmCalls = [...drCalls, ...dwCalls, ...arCalls, ...awCalls];
  if (nonPmCalls.length > 0) {
    record.usedAt = nonPmCalls.map((c) => ({
      line: c.line,
      operation: c.op,
    }));
  }
}
 
/**
 * Convert PinMode string to numeric representation for legacy compatibility.
 */
function convertModeToNumeric(mode: PinMode | undefined): number {
  switch (mode) {
    case "INPUT":
      return 0;
    case "OUTPUT":
      return 1;
    case "INPUT_PULLUP":
      return 2;
    default:
      return 0;
  }
}
 
/**
 * Build a single IOPinRecord from aggregated call entries for a pin.
 */
function buildPinRecord(
  pinId: number,
  calls: StaticIOCall[],
  pmCalls: StaticIOCall[],
  drCalls: StaticIOCall[],
  dwCalls: StaticIOCall[],
  arCalls: StaticIOCall[],
  awCalls: StaticIOCall[],
): IOPinRecord {
  const label = pinId >= 14 ? `A${pinId - 14}` : String(pinId);
 
  const conflicts = detectPinConflicts(
    pmCalls,
    drCalls,
    dwCalls,
    arCalls,
    awCalls,
  );
 
  const conflict =
    conflicts.pinModeConflict ||
    conflicts.operationConflict ||
    conflicts.outputReadConflict;
 
  const record: IOPinRecord = {
    pin: label,
    pinId,
    defined: calls.length > 0,
  };
 
  if (conflict) {
    record.conflict = true;
    record.conflictMessage = generateConflictMessage(
      conflicts.pinModeConflict,
      conflicts.operationConflict,
      conflicts.outputReadConflict,
      conflicts.uniqueModes,
    );
  }
 
  populateLineArrays(record, pmCalls, drCalls, dwCalls, arCalls, awCalls);
  populateLegacyFields(record, pmCalls, drCalls, dwCalls, arCalls, awCalls);
 
  return record;
}
 
/** Analyze statically resolvable Arduino I/O usage without applying a UI projection. */
export function analyzeStaticIO(code: string): StaticIOAnalysis {
  const clean = stripComments(code);
  const { values: syms, userSymbols } = buildSymbols(clean);
  const arrays = buildArrays(clean, syms);
  const loops = findLoopRanges(clean, syms);
 
  const entries: StaticIOCall[] = [];
  const unresolvedCalls: UnresolvedStaticIOCall[] = [];
 
  /**
   * Regex captures:
   *   [1] function name
   *   [2] pin expression: array-index form OR simple token/number
   *   [3] optional second argument (mode for pinMode, ignored otherwise)
   */
 
  let m: RegExpExecArray | null;
  while ((m = FUNCTION_CALL_PATTERN.exec(clean)) !== null) {
    const op = m[1] as StaticIOOperation;
    const pinExpr = m[2].trim();
    const secondArg = (m[3] ?? "").trim();
    const callPos = m.index;
    const callLine = lineAt(clean, callPos);
 
    processCallExpression(
      op,
      pinExpr,
      secondArg,
      callPos,
      callLine,
      { loops, syms, arrays, entries, unresolvedCalls },
    );
  }
 
  // ── Aggregate entries by pinId ────────────────────────────────────────────
  const pinMap = new Map<number, StaticIOCall[]>();
  for (const entry of entries) {
    const existing = pinMap.get(entry.pinId);
    if (existing) {
      existing.push(entry);
    } else {
      pinMap.set(entry.pinId, [entry]);
    }
  }
 
  const pins = [...pinMap].map(([pinId, calls]) => ({ pinId, calls }));
  pins.sort((a, b) => a.pinId - b.pinId);
  const symbols = Object.fromEntries(
    [...userSymbols].map((name) => [name, syms.get(name) as number]),
  );
  return { pins, unresolvedCalls, symbols };
}
 
/** Project canonical static I/O facts to the existing registry contract. */
function buildStaticIORegistry(analysis: StaticIOAnalysis): IOPinRecord[] {
  const records: IOPinRecord[] = [];
 
  for (const { pinId, calls } of analysis.pins) {
    const pmCalls = calls.filter((c) => c.op === "pinMode");
    const drCalls = calls.filter((c) => c.op === "digitalRead");
    const dwCalls = calls.filter((c) => c.op === "digitalWrite");
    const arCalls = calls.filter((c) => c.op === "analogRead");
    const awCalls = calls.filter((c) => c.op === "analogWrite");
 
    const record = buildPinRecord(
      pinId,
      calls,
      pmCalls,
      drCalls,
      dwCalls,
      arCalls,
      awCalls,
    );
 
    records.push(record);
  }
 
  // Sort by pinId (0 → 19)
  return records.sort((a, b) => (a.pinId ?? 0) - (b.pinId ?? 0));
}
 
/**
 * Statically parse an Arduino sketch and return an IOPinRecord[] for every pin
 * usage found in the source code.
 *
 * – Populates `pinModeLines`, `digitalReadLines`, `digitalWriteLines`,
 *   `analogReadLines`, `analogWriteLines` for the extended (eye-on) view.
 * – Sets `conflict = true` for TC 9 (write on input-mode pin) and
 *   TC 11 (same pin configured with multiple different modes).
 * – Dynamically-resolved pins (TC 8) are silently skipped; they will be
 *   filled in by the runtime path.
 * – Populates legacy `pinMode`, `definedAt`, `usedAt` fields for backward
 *   compatibility with the existing UI and runtime registry manager.
 */
export function parseStaticIORegistry(code: string): IOPinRecord[] {
  return buildStaticIORegistry(analyzeStaticIO(code));
}
 
const PROJECT_DEFINE_PATTERN = /^\s*#define\s+([A-Za-z_]\w*)\s+(\w+)/;
const PROJECT_CONST_PATTERN = /\bconst\s+(?:int|byte|uint8_t|uint16_t|short|long)\s+([A-Za-z_]\w*)\s*=\s*(\w+)\s*;/;
const PROJECT_VAR_PATTERN = /\b(?:int|byte|uint8_t)\s+([A-Za-z_]\w*)\s*=\s*(\w+)\s*;/;
const PROJECT_ARRAY_TYPES = new Set(["int", "byte", "uint8_t"]);
 
interface SourceToken {
  value: string;
  start: number;
  end: number;
}
 
interface ProjectArrayDeclaration {
  name: string;
  values: string;
  index: number;
  end: number;
}
 
function isIdentifierStart(character: string | undefined): boolean {
  if (!character) return false;
  const code = character.codePointAt(0) ?? 0;
  return character === "_" || (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
}
 
function isIdentifierPart(character: string | undefined): boolean {
  if (isIdentifierStart(character)) return true;
  const code = character?.codePointAt(0) ?? 0;
  return code >= 48 && code <= 57;
}
 
function skipSourceWhitespace(source: string, start: number): number {
  let index = start;
  while (index < source.length && /\s/.test(source[index])) index++;
  return index;
}
 
function readIdentifier(source: string, start: number): SourceToken | undefined {
  if (!isIdentifierStart(source[start])) return undefined;
  let end = start + 1;
  while (end < source.length && isIdentifierPart(source[end])) end++;
  return { value: source.slice(start, end), start, end };
}
 
function findNextIdentifier(source: string, start: number): SourceToken | undefined {
  let index = start;
  while (index < source.length && !isIdentifierStart(source[index])) index++;
  return readIdentifier(source, index);
}
 
function isValidArraySize(value: string): boolean {
  if (value.length === 0) return true;
  Eif (readIdentifier(value, 0)?.end === value.length) return true;
  return [...value].every((character) => character >= "0" && character <= "9");
}
 
function readArrayDeclarationHead(
  source: string,
  start: number,
): { name: string; index: number; nextIndex: number } | undefined {
  const first = readIdentifier(source, start);
  Iif (!first) return undefined;
 
  let type = first;
  if (first.value === "const") {
    const typeStart = skipSourceWhitespace(source, first.end);
    Iif (typeStart === first.end) return undefined;
    const constType = readIdentifier(source, typeStart);
    Iif (!constType) return undefined;
    type = constType;
  }
  if (!PROJECT_ARRAY_TYPES.has(type.value)) return undefined;
 
  const nameStart = skipSourceWhitespace(source, type.end);
  Iif (nameStart === type.end) return undefined;
  const name = readIdentifier(source, nameStart);
  Iif (!name) return undefined;
  return { name: name.value, index: first.start, nextIndex: name.end };
}
 
function readProjectArrayDeclaration(
  source: string,
  start: number,
): ProjectArrayDeclaration | undefined {
  const head = readArrayDeclarationHead(source, start);
  if (!head) return undefined;
 
  let cursor = skipSourceWhitespace(source, head.nextIndex);
  if (source[cursor] !== "[") return undefined;
  const closeBracket = source.indexOf("]", cursor + 1);
  Iif (closeBracket < 0) return undefined;
  const size = source.slice(cursor + 1, closeBracket).trim();
  Iif (!isValidArraySize(size)) return undefined;
 
  cursor = skipSourceWhitespace(source, closeBracket + 1);
  Iif (source[cursor] !== "=") return undefined;
  cursor = skipSourceWhitespace(source, cursor + 1);
  Iif (source[cursor] !== "{") return undefined;
  const closeBrace = source.indexOf("}", cursor + 1);
  Iif (closeBrace <= cursor + 1) return undefined;
 
  return {
    name: head.name,
    values: source.slice(cursor + 1, closeBrace),
    index: head.index,
    end: closeBrace + 1,
  };
}
 
function findProjectArrayDeclarations(source: string): ProjectArrayDeclaration[] {
  const declarations: ProjectArrayDeclaration[] = [];
  let cursor = 0;
  while (cursor < source.length) {
    const token = findNextIdentifier(source, cursor);
    if (!token) break;
    const declaration = readProjectArrayDeclaration(source, token.start);
    if (declaration) declarations.push(declaration);
    cursor = declaration?.end ?? token.end;
  }
  return declarations;
}
 
function registerProjectSymbols(
  line: string,
  syms: Map<string, number>,
  userSymbols: Set<string>,
  arrays: Map<string, number[]>,
  throughIndex = line.length,
): void {
  const definitions = [PROJECT_DEFINE_PATTERN, PROJECT_CONST_PATTERN, PROJECT_VAR_PATTERN];
  for (const definition of definitions) {
    const pattern = new RegExp(definition.source, "g");
    let match: RegExpExecArray | null;
    while ((match = pattern.exec(line)) !== null) {
      if (match.index > throughIndex) break;
      const value = resolveToken(match[2], syms);
      Eif (value !== undefined) {
        syms.set(match[1], value);
        userSymbols.add(match[1]);
      }
    }
  }
 
  for (const declaration of findProjectArrayDeclarations(line)) {
    Iif (declaration.index > throughIndex) break;
    const values = declaration.values
      .split(",")
      .map((value) => resolveToken(value.trim(), syms));
    Eif (values.every((value): value is number => value !== undefined)) {
      arrays.set(declaration.name, values);
    }
  }
}
 
function annotateProjectEntries(
  entries: StaticIOCall[],
  unresolvedCalls: UnresolvedStaticIOCall[],
  entryCount: number,
  unresolvedCount: number,
  location: SourceLocation,
  sourceOrder: number,
): void {
  for (let index = entryCount; index < entries.length; index++) {
    entries[index].file = location.file;
    entries[index].line = location.line;
    entries[index].sourceOrder = sourceOrder;
  }
  for (let index = unresolvedCount; index < unresolvedCalls.length; index++) {
    unresolvedCalls[index].file = location.file;
    unresolvedCalls[index].line = location.line;
    unresolvedCalls[index].sourceOrder = sourceOrder;
  }
}
 
function analyzeResolvedStaticIOProject(
  resolved: ResolvedSourceProject,
): StaticIOProjectAnalysis {
  const cleanLines = stripComments(resolved.source).split("\n");
  const syms = new Map<string, number>(Object.entries(BUILTIN_CONSTANTS));
  const userSymbols = new Set<string>();
  const arrays = new Map<string, number[]>();
  const entries: StaticIOCall[] = [];
  const unresolvedCalls: UnresolvedStaticIOCall[] = [];
  let offset = 0;
 
  for (let lineIndex = 0; lineIndex < cleanLines.length; lineIndex++) {
    const cleanLine = cleanLines[lineIndex] ?? "";
    const location = resolved.lineOrigins[lineIndex] ?? {
      file: resolved.entryFile,
      line: lineIndex + 1,
    };
 
    FUNCTION_CALL_PATTERN.lastIndex = 0;
    let match: RegExpExecArray | null;
    while ((match = FUNCTION_CALL_PATTERN.exec(cleanLine)) !== null) {
      const entryCount = entries.length;
      const unresolvedCount = unresolvedCalls.length;
      const op = match[1] as StaticIOOperation;
      const pinExpr = match[2].trim();
      const secondArg = (match[3] ?? "").trim();
      const callPos = offset + match.index;
      // Register only definitions that occur before this call. This preserves
      // source order even when a declaration and a use share one line.
      registerProjectSymbols(cleanLine, syms, userSymbols, arrays, match.index);
      const loops = findLoopRanges(resolved.source, syms);
 
      processCallExpression(
        op,
        pinExpr,
        secondArg,
        callPos,
        lineIndex + 1,
        { loops, syms, arrays, entries, unresolvedCalls },
      );
      annotateProjectEntries(
        entries,
        unresolvedCalls,
        entryCount,
        unresolvedCount,
        location,
        lineIndex,
      );
    }
    registerProjectSymbols(cleanLine, syms, userSymbols, arrays);
    offset += cleanLine.length + 1;
  }
 
  const pinMap = new Map<number, StaticIOCall[]>();
  for (const entry of entries) {
    const existing = pinMap.get(entry.pinId);
    if (existing) existing.push(entry);
    else pinMap.set(entry.pinId, [entry]);
  }
  const pins = [...pinMap]
    .map(([pinId, calls]) => ({ pinId, calls }))
    .sort((a, b) => a.pinId - b.pinId);
  const symbols = Object.fromEntries(
    [...userSymbols].map((name) => [name, syms.get(name) as number]),
  );
  return {
    pins,
    unresolvedCalls,
    symbols,
    diagnostics: resolved.diagnostics,
    complete: resolved.complete,
    resolved,
  };
}
 
/** Analyze only the entry-reachable local source files in include order. */
export function analyzeStaticIOProject(
  project: SourceProject,
): StaticIOProjectAnalysis {
  return analyzeResolvedStaticIOProject(resolveSourceProject(project));
}
 
function locationsFor(
  calls: StaticIOCall[],
  operation: StaticIOOperation,
): SourceLocation[] {
  return calls
    .filter((call) => call.op === operation && call.file !== undefined)
    .sort((a, b) => (a.sourceOrder ?? 0) - (b.sourceOrder ?? 0))
    .map((call) => ({ file: call.file as string, line: call.line }));
}
 
/** Project-aware registry projection with additive file/line locations. */
export function parseStaticIORegistryProject(
  project: SourceProject,
): StaticIOProjectPinRecord[] {
  const analysis = analyzeStaticIOProject(project);
  const records = buildStaticIORegistry(analysis) as StaticIOProjectPinRecord[];
  for (const record of records) {
    const calls = analysis.pins.find(({ pinId }) => pinId === record.pinId)?.calls ?? [];
    const pinModeLocations = locationsFor(calls, "pinMode");
    const digitalReadLocations = locationsFor(calls, "digitalRead");
    const digitalWriteLocations = locationsFor(calls, "digitalWrite");
    const analogReadLocations = locationsFor(calls, "analogRead");
    const analogWriteLocations = locationsFor(calls, "analogWrite");
    if (pinModeLocations.length > 0) record.pinModeLocations = pinModeLocations;
    Iif (digitalReadLocations.length > 0) record.digitalReadLocations = digitalReadLocations;
    if (digitalWriteLocations.length > 0) record.digitalWriteLocations = digitalWriteLocations;
    if (analogReadLocations.length > 0) record.analogReadLocations = analogReadLocations;
    Iif (analogWriteLocations.length > 0) record.analogWriteLocations = analogWriteLocations;
  }
  return records;
}