All files / shared code-parser.ts

97.89% Statements 186/190
91.26% Branches 94/103
100% Functions 10/10
98.36% Lines 181/184

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  8x                 65x     65x       65x 65x     65x 35x       30x 30x       30x 14x   6x                       8x                       16x     16x 10x                               30x 2x                         30x 30x 264x   264x   4x 4x 14x 1x 1x       4x 3x                   3x         30x             62x     62x 62x     62x   62x   1x                   61x 5x                       62x 62x     62x   62x                       62x 7x                     62x               68x         68x     68x 1x 1x     1x 7x       68x     68x     68x     68x   68x 9x 9x   9x 3x                               68x 68x 68x 17x       68x   68x 68x         68x 17x 17x 17x   17x 16x   1x 1x 1x       68x 16x   1x 1x   1x 1x                                             68x       68x 68x 68x   68x 12x 12x   12x   10x   10x         2x 2x                                 68x 68x 68x 6x       68x 10x   2x 1x                       1x               68x     68x 55x 55x 1x                             68x             66x     66x   66x   66x 39x 39x 39x         66x 66x 66x 13x 13x 13x         66x 23x 11x 11x                     66x             70x     70x 6x                         70x 70x 2x                         70x 70x 70x 3x 3x 3x                               70x 70x     70x 134x 134x     134x 134x 134x   134x 6148x 144x 144x 6004x 144x 144x 134x 134x           134x           134x   134x 134x 3x                             70x             57x                           400x   400x 400x             71x   18x 18x 18x       53x 53x 53x                         43x 43x 43x   43x 43x 43x      
import type { ParserMessage } from "./schema";
import { randomUUID } from "crypto";
 
type SeverityLevel = 1 | 2 | 3;
 
export class CodeParser {
  /**
   * Parse Serial configuration issues
   */
  parseSerialConfiguration(code: string): ParserMessage[] {
    const messages: ParserMessage[] = [];
 
    // Remove comments to check active code
    const uncommentedCode = this.removeComments(code);
 
    // Check if Serial is actually used (print, println, read, write, available, etc.)
    const serialUsageRegex =
      /Serial\s*\.\s*(print|println|write|read|available|peek|readString|readBytes|parseInt|parseFloat|find|findUntil)/;
    const isSerialUsed = serialUsageRegex.test(uncommentedCode);
 
    // Only check Serial.begin if Serial is actually being used
    if (!isSerialUsed) {
      return messages; // No Serial usage, no warnings needed
    }
 
    // Check if Serial.begin exists at all
    const serialBeginExists = /Serial\s*\.\s*begin\s*\(\s*\d+\s*\)/.test(code);
    const serialBeginActive = /Serial\s*\.\s*begin\s*\(\s*\d+\s*\)/.test(
      uncommentedCode,
    );
 
    if (!serialBeginActive) {
      if (serialBeginExists) {
        // Serial.begin exists but is commented out
        messages.push({
          id: randomUUID(),
          type: "warning",
          category: "serial",
          severity: 2 as SeverityLevel,
          message:
            "Serial.begin() is commented out! Serial output may not work correctly.",
          suggestion: "Serial.begin(115200);",
          line: this.findLineNumber(code, /Serial\s*\.\s*begin/),
        });
      } else {
        // Serial.begin missing entirely
        messages.push({
          id: randomUUID(),
          type: "warning",
          category: "serial",
          severity: 2 as SeverityLevel,
          message:
            "Serial.begin(115200) is missing in setup(). Serial output may not work correctly.",
          suggestion: "Serial.begin(115200);",
        });
      }
    } else {
      // Check baudrate
      const baudRateMatch = uncommentedCode.match(
        /Serial\s*\.\s*begin\s*\(\s*(\d+)\s*\)/,
      );
      if (baudRateMatch && baudRateMatch[1] !== "115200") {
        messages.push({
          id: randomUUID(),
          type: "warning",
          category: "serial",
          severity: 2 as SeverityLevel,
          message: `Serial.begin(${baudRateMatch[1]}) uses wrong baud rate. This simulator expects Serial.begin(115200).`,
          suggestion: "Serial.begin(115200);",
          line: this.findLineNumber(
            code,
            new RegExp(`Serial\\s*\\.\\s*begin\\s*\\(\\s*${baudRateMatch[1]}`),
          ),
        });
      }
    }
 
    // Check for while (!Serial) antipattern
    if (/while\s*\(\s*!\s*Serial\s*\)/.test(uncommentedCode)) {
      messages.push({
        id: randomUUID(),
        type: "warning",
        category: "serial",
        severity: 2 as SeverityLevel,
        message:
          "while (!Serial) loop detected. This blocks the simulator - not recommended.",
        suggestion: "// while (!Serial) { }",
        line: this.findLineNumber(code, /while\s*\(\s*!\s*Serial\s*\)/),
      });
    }
 
    // Check for Serial.read() without Serial.available() check
    const lines = uncommentedCode.split("\n");
    for (let i = 0; i < lines.length; i++) {
      const line = lines[i];
      // Check if line has Serial.read() but not preceded by Serial.available check
      if (/Serial\s*\.\s*read\s*\(\s*\)/.test(line)) {
        // Look back to see if there's an available check nearby
        let hasAvailableCheck = false;
        for (let j = Math.max(0, i - 3); j <= i; j++) {
          if (/Serial\s*\.\s*available\s*\(\s*\)/.test(lines[j])) {
            hasAvailableCheck = true;
            break;
          }
        }
 
        if (!hasAvailableCheck) {
          messages.push({
            id: randomUUID(),
            type: "warning",
            category: "serial",
            severity: 2 as SeverityLevel,
            message:
              "Serial.read() used without checking Serial.available(). This may return -1 when no data is available.",
            suggestion: "if (Serial.available()) { }",
            line: this.findLineNumber(code, /Serial\s*\.\s*read\s*\(\s*\)/),
          });
          break; // Only report once
        }
      }
    }
 
    return messages;
  }
 
  /**
   * Parse structure issues (setup/loop)
   */
  parseStructure(code: string): ParserMessage[] {
    const messages: ParserMessage[] = [];
 
    // Check for void setup() with proper signatures
    const setupRegex = /void\s+setup\s*\(\s*\)/;
    const setupMatch = setupRegex.test(code);
 
    // Check for any setup() function (even with wrong signature)
    const anySetup = /void\s+setup\s*\([^)]*\)/.test(code);
 
    if (!setupMatch && anySetup) {
      // setup() exists but has parameters
      messages.push({
        id: randomUUID(),
        type: "warning",
        category: "structure",
        severity: 2 as SeverityLevel,
        message:
          "setup() has parameters, but Arduino setup() should have no parameters.",
        suggestion: "void setup()",
        line: this.findLineNumber(code, /void\s+setup\s*\(/),
      });
    } else if (!setupMatch) {
      messages.push({
        id: randomUUID(),
        type: "error",
        category: "structure",
        severity: 3 as SeverityLevel,
        message:
          "Missing void setup() function. Every Arduino program needs setup().",
        suggestion: "void setup() { }",
      });
    }
 
    // Check for void loop()
    const loopRegex = /void\s+loop\s*\(\s*\)/;
    const loopMatch = loopRegex.test(code);
 
    // Check for any loop() function
    const anyLoop = /void\s+loop\s*\([^)]*\)/.test(code);
 
    Iif (!loopMatch && anyLoop) {
      // loop() exists but has parameters
      messages.push({
        id: randomUUID(),
        type: "warning",
        category: "structure",
        severity: 2 as SeverityLevel,
        message:
          "loop() has parameters, but Arduino loop() should have no parameters.",
        suggestion: "void loop()",
        line: this.findLineNumber(code, /void\s+loop\s*\(/),
      });
    } else if (!loopMatch) {
      messages.push({
        id: randomUUID(),
        type: "error",
        category: "structure",
        severity: 3 as SeverityLevel,
        message:
          "Missing void loop() function. Every Arduino program needs loop().",
        suggestion: "void loop() { }",
      });
    }
 
    return messages;
  }
 
  /**
   * Detect pins configured in loops (e.g., for i=0; i<7 with pinMode(i, ...)
   * Returns Set of numeric pin numbers that are likely configured by loop
   */
  private getLoopConfiguredPins(code: string): Set<number> {
    const configuredPins = new Set<number>();
 
    // Find for loops with pinMode calls using loop variable
    // Pattern: for (type var = start; var < end; ...) { ... pinMode(var, ...) ... }
    const loopRegex =
      /for\s*\(\s*(?:byte|int|var)?\s*([a-zA-Z_]\w*)\s*=\s*(\d+)\s*;\s*\1\s*<\s*(\d+)\s*;[^)]*\)\s*\{[^}]*pinMode\s*\(\s*\1\s*,/gi;
    let match;
 
    while ((match = loopRegex.exec(code)) !== null) {
      const startVal = parseInt(match[2], 10);
      const endVal = parseInt(match[3], 10);
 
      // Add all pins that would be configured by this loop (start to end-1)
      for (let i = startVal; i < endVal; i++) {
        configuredPins.add(i);
      }
    }
 
    return configuredPins;
  }
  parseHardwareCompatibility(code: string): ParserMessage[] {
    const messages: ParserMessage[] = [];
 
    // Valid PWM pins on Arduino UNO: 3, 5, 6, 9, 10, 11
    const PWM_PINS = [3, 5, 6, 9, 10, 11];
 
    // Check for analogWrite on non-PWM pins
    const analogWriteRegex = /analogWrite\s*\(\s*(\d+|A\d+)\s*,/g;
    let match;
    while ((match = analogWriteRegex.exec(code)) !== null) {
      const pinStr = match[1];
      const pin = this.parsePinNumber(pinStr);
 
      if (pin !== undefined && !PWM_PINS.includes(pin)) {
        messages.push({
          id: randomUUID(),
          type: "warning",
          category: "hardware",
          severity: 2 as SeverityLevel,
          message: `analogWrite(${pinStr}, ...) used on pin ${pin}, which doesn't support PWM on Arduino UNO. PWM pins: 3, 5, 6, 9, 10, 11.`,
          suggestion: `// Use PWM pin instead: analogWrite(3, value);`,
          line: this.findLineNumber(
            code,
            new RegExp(`analogWrite\\s*\\(\\s*${pinStr}`),
          ),
        });
      }
    }
 
    // Check for pinMode declarations
    const pinModeSet = new Set<string>();
    const pinModeRegex = /pinMode\s*\(\s*(\d+|A\d+)\s*,/g;
    while ((match = pinModeRegex.exec(code)) !== null) {
      pinModeSet.add(match[1]);
    }
 
    // Detect multiple pinMode calls for the same pin
    const uncommentedCode = this.removeComments(code);
    const pinModeWithModeRegex =
      /pinMode\s*\(\s*(\d+|A\d+)\s*,\s*(INPUT_PULLUP|INPUT|OUTPUT)\s*\)/g;
    const pinModeCalls = new Map<
      string,
      { modes: Array<"INPUT" | "OUTPUT" | "INPUT_PULLUP">; lines: number[] }
    >();
 
    while ((match = pinModeWithModeRegex.exec(uncommentedCode)) !== null) {
      const pin = match[1];
      const mode = match[2] as "INPUT" | "OUTPUT" | "INPUT_PULLUP";
      const line = uncommentedCode.substring(0, match.index).split("\n").length;
 
      if (!pinModeCalls.has(pin)) {
        pinModeCalls.set(pin, { modes: [mode], lines: [line] });
      } else {
        const entry = pinModeCalls.get(pin)!;
        entry.modes.push(mode);
        entry.lines.push(line);
      }
    }
 
    for (const [pin, entry] of pinModeCalls.entries()) {
      if (entry.modes.length < 2) continue;
 
      const uniqueModes = Array.from(new Set(entry.modes));
      const line = entry.lines[1];
 
      if (uniqueModes.length > 1) {
        messages.push({
          id: randomUUID(),
          type: "warning",
          category: "pins",
          severity: 2 as SeverityLevel,
          message: `Pin ${pin} has multiple pinMode() calls with different modes: ${uniqueModes.join(", ")}.`,
          suggestion: `Use a single pinMode(${pin}, <MODE>) call in setup().`,
          line,
        });
      } else E{
        messages.push({
          id: randomUUID(),
          type: "warning",
          category: "pins",
          severity: 2 as SeverityLevel,
          message: `Pin ${pin} has pinMode() called multiple times (${entry.modes.length}x).`,
          suggestion: `Remove duplicate pinMode(${pin}, ${uniqueModes[0]}) calls.`,
          line,
        });
      }
    }
 
    // Also detect pins configured in loops
    const loopConfiguredPins = this.getLoopConfiguredPins(code);
 
    // Check for digitalRead/digitalWrite without pinMode
    const digitalReadWriteRegex =
      /digital(?:Read|Write)\s*\(\s*(\d+|A\d+|[a-zA-Z_]\w*)/g;
    const warnedPins = new Set<string>();
    const usedVariables = new Set<string>();
 
    while ((match = digitalReadWriteRegex.exec(code)) !== null) {
      const pinStr = match[1];
      usedVariables.add(pinStr); // Track all variable/pin references
 
      if (/^\d+/.test(pinStr) || /^A\d+/.test(pinStr)) {
        // Literal pin number
        const pin = this.parsePinNumber(pinStr);
        // Only warn if not explicitly configured with pinMode AND not in a loop range
        if (
          !pinModeSet.has(pinStr) &&
          (pin === undefined || !loopConfiguredPins.has(pin)) &&
          !warnedPins.has(pinStr)
        ) {
          warnedPins.add(pinStr);
          messages.push({
            id: randomUUID(),
            type: "warning",
            category: "hardware",
            severity: 2 as SeverityLevel,
            message: `Pin ${pinStr} used with digitalRead/digitalWrite but pinMode() was not called for this pin.`,
            suggestion: `pinMode(${pinStr}, INPUT);`,
            line: this.findLineNumber(
              code,
              new RegExp(`digital(?:Read|Write)\\s*\\(\\s*${pinStr}`),
            ),
          });
        }
      }
    }
 
    // Check if variable pins are used with pinMode - warn if there's a mismatch
    const pinModeVarRegex = /pinMode\s*\(\s*([a-zA-Z_]\w*)\s*,/g;
    const pinModeVariables = new Set<string>();
    while ((match = pinModeVarRegex.exec(this.removeComments(code))) !== null) {
      pinModeVariables.add(match[1]);
    }
 
    // Warn if digitalRead/digitalWrite uses variables not covered by pinMode
    for (const usedVar of usedVariables) {
      if (!/^\d+/.test(usedVar) && !/^A\d+/.test(usedVar)) {
        // It's a variable
        if (!pinModeVariables.has(usedVar)) {
          messages.push({
            id: randomUUID(),
            type: "warning",
            category: "hardware",
            severity: 2 as SeverityLevel,
            message: `Variable '${usedVar}' used in digitalRead/digitalWrite but no pinMode() call found for this variable.`,
            suggestion: `pinMode(${usedVar}, INPUT);`,
            line: this.findLineNumber(
              code,
              new RegExp(`digital(?:Read|Write)\\s*\\(\\s*${usedVar}`),
            ),
          });
          break; // Only warn once per unique variable
        }
      }
    }
 
    // Handle dynamic pin usage (e.g., digitalRead(i)) where pin numbers are not literals.
    // Only warn if NO pinMode calls exist at all. If pinMode is called (even in a loop),
    // we assume pins are being configured dynamically.
    const hasPinModeCalls = /pinMode\s*\(\s*[^,)]+\s*,/.test(
      this.removeComments(code),
    );
    if (!hasPinModeCalls) {
      const dynamicDigitalUse = /digital(?:Read|Write)\s*\(\s*[^0-9A\s][^,)]*/;
      if (dynamicDigitalUse.test(this.removeComments(code))) {
        messages.push({
          id: randomUUID(),
          type: "warning",
          category: "hardware",
          severity: 2 as SeverityLevel,
          message:
            "digitalRead/digitalWrite uses variable pins without any pinMode() calls. Configure pinMode for the pins being read/written.",
          suggestion: "pinMode(<pin>, INPUT);",
          line: this.findLineNumber(code, /digital(?:Read|Write)\s*\(/),
        });
      }
    }
 
    // SPI and I2C pin warnings removed - not necessary for simulation
 
    return messages;
  }
 
  /**
   * Parse pin conflicts (same pin used as digital and analog)
   */
  parsePinConflicts(code: string): ParserMessage[] {
    const messages: ParserMessage[] = [];
 
    // Find all pins used in digitalWrite/digitalRead/pinMode
    const digitalPins = new Set<number>();
    const digitalRegex =
      /(?:digital(?:Write|Read)|pinMode)\s*\(\s*(\d+|A\d+)/gi;
    let match;
    while ((match = digitalRegex.exec(code)) !== null) {
      const pin = this.parsePinNumber(match[1]);
      Eif (pin !== undefined) {
        digitalPins.add(pin);
      }
    }
 
    // Find all pins used in analogRead/analogWrite
    const analogPins = new Set<number>();
    const analogRegex = /analog(?:Read|Write)\s*\(\s*(\d+|A\d+)/gi;
    while ((match = analogRegex.exec(code)) !== null) {
      const pin = this.parsePinNumber(match[1]);
      Eif (pin !== undefined) {
        analogPins.add(pin);
      }
    }
 
    // Find conflicts
    for (const pin of digitalPins) {
      if (analogPins.has(pin)) {
        const pinStr = pin >= 14 ? `A${pin - 14}` : `${pin}`;
        messages.push({
          id: randomUUID(),
          type: "warning",
          category: "hardware",
          severity: 2 as SeverityLevel,
          message: `Pin ${pinStr} used as both digital (digitalWrite/digitalRead) and analog (analogRead/analogWrite). This may be unintended.`,
          suggestion: `// Use separate pins for digital and analog`,
        });
      }
    }
 
    return messages;
  }
 
  /**
   * Parse performance issues
   */
  parsePerformance(code: string): ParserMessage[] {
    const messages: ParserMessage[] = [];
 
    // Check for while (true) loops
    if (/while\s*\(\s*true\s*\)/.test(code)) {
      messages.push({
        id: randomUUID(),
        type: "warning",
        category: "performance",
        severity: 2 as SeverityLevel,
        message:
          "Infinite while(true) loop detected. This may freeze the simulator.",
        suggestion: "delay(100);",
        line: this.findLineNumber(code, /while\s*\(\s*true\s*\)/),
      });
    }
 
    // Check for for loops without exit condition
    const forLoopRegex = /for\s*\(\s*[^;]+;\s*;\s*[^)]+\)/;
    if (forLoopRegex.test(code)) {
      messages.push({
        id: randomUUID(),
        type: "warning",
        category: "performance",
        severity: 2 as SeverityLevel,
        message:
          "for loop without exit condition detected. This creates an infinite loop.",
        suggestion: "for (int i = 0; i < 10; i++) { }",
        line: this.findLineNumber(code, forLoopRegex),
      });
    }
 
    // Check for large arrays
    const arrayRegex = /\[\s*(\d{4,})\s*\]/;
    const arrayMatch = code.match(arrayRegex);
    if (arrayMatch) {
      const arraySize = parseInt(arrayMatch[1]);
      Eif (arraySize > 1000) {
        messages.push({
          id: randomUUID(),
          type: "warning",
          category: "performance",
          severity: 2 as SeverityLevel,
          message: `Large array of ${arraySize} elements detected. This may cause memory issues on Arduino.`,
          suggestion: `// Use smaller array size: int array[100];`,
          line: this.findLineNumber(code, arrayRegex),
        });
      }
    }
 
    // Check for recursion
    // Match function definitions: return_type function_name(params) { ... }
    // Exclude keywords like if, for, while, switch
    const functionDefinitionRegex =
      /(?:void|int|bool|byte|long|float|double|char|String|unsigned\s+int|unsigned\s+long)\s+(\w+)\s*\([^)]*\)\s*\{/g;
    const uncommentedCode = this.removeComments(code);
 
    let match;
    while ((match = functionDefinitionRegex.exec(uncommentedCode)) !== null) {
      const functionName = match[1];
      const functionStart = match.index;
 
      // Find the end of this function by counting braces
      let braceCount = 0;
      let foundOpenBrace = false;
      let functionEnd = functionStart;
 
      for (let i = functionStart; i < uncommentedCode.length; i++) {
        if (uncommentedCode[i] === "{") {
          braceCount++;
          foundOpenBrace = true;
        } else if (uncommentedCode[i] === "}") {
          braceCount--;
          if (foundOpenBrace && braceCount === 0) {
            functionEnd = i;
            break;
          }
        }
      }
 
      // Extract function body
      const functionBody = uncommentedCode.substring(
        functionStart,
        functionEnd + 1,
      );
 
      // Check if function calls itself (recursive)
      const functionCallRegex = new RegExp(`\\b${functionName}\\s*\\(`, "g");
      // Count calls - there should be the definition itself, so if we find more than 1, it's recursive
      const calls = functionBody.match(functionCallRegex);
      if (calls && calls.length > 1) {
        messages.push({
          id: randomUUID(),
          type: "warning",
          category: "performance",
          severity: 2 as SeverityLevel,
          message: `Recursive function '${functionName}' detected. Deep recursion may cause stack overflow on Arduino.`,
          suggestion: "// Use iterative approach instead",
          line: this.findLineNumber(
            code,
            new RegExp(`\\b${functionName}\\s*\\(`),
          ),
        });
      }
    }
 
    return messages;
  }
 
  /**
   * Parse all categories and combine results
   */
  parseAll(code: string): ParserMessage[] {
    return [
      ...this.parseSerialConfiguration(code),
      ...this.parseStructure(code),
      ...this.parseHardwareCompatibility(code),
      ...this.parsePinConflicts(code),
      ...this.parsePerformance(code),
    ];
  }
 
  /**
   * Remove comments from code (both single-line and multi-line)
   */
  private removeComments(code: string): string {
    // Remove single-line comments
    let result = code.replace(/\/\/.*$/gm, "");
    // Remove multi-line comments
    result = result.replace(/\/\*[\s\S]*?\*\//g, "");
    return result;
  }
 
  /**
   * Parse pin number from string (e.g., "13" or "A0")
   */
  private parsePinNumber(pinStr: string): number | undefined {
    if (/^A\d+$/.test(pinStr)) {
      // Analog pin (A0-A5 map to 14-19 internally)
      const analogNum = parseInt(pinStr.substring(1));
      Eif (analogNum >= 0 && analogNum <= 5) {
        return 14 + analogNum;
      }
    } else {
      // Digital pin
      const digitalNum = parseInt(pinStr);
      Eif (!isNaN(digitalNum) && digitalNum >= 0 && digitalNum <= 19) {
        return digitalNum;
      }
    }
    return undefined;
  }
 
  /**
   * Find line number where pattern occurs
   */
  private findLineNumber(
    code: string,
    pattern: RegExp | string,
  ): number | undefined {
    const regex = typeof pattern === "string" ? new RegExp(pattern) : pattern;
    const match = regex.exec(code);
    Iif (!match) return undefined;
 
    const upToMatch = code.substring(0, match.index);
    const lineNumber = upToMatch.split("\n").length;
    return lineNumber;
  }
}