All files / client/src/hooks use-sketch-analysis.ts

92.56% Statements 112/121
80.3% Branches 53/66
94.11% Functions 16/17
95.74% Lines 90/94

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                              2x     2x     2x     2x     2x     2x       3x 3x 63x 3x 63x   3x           2x   2x   2x     2x           19x 19x 5x 5x                   7x 7x 7x 1x           6x               11x 11x 9x 6x                 2x 2x 1x 1x 1x             2x 1x               10x     10x 10x 1x 1x       10x 5x 5x     10x               10x 10x   10x 11x 11x 11x 11x 11x   10x         10x   10x 4x 4x 3x 3x 3x 3x       3x 3x 3x 4x 10x 4x       10x 10x 10x   10x                   10x 10x 10x   10x 2x 2x 2x 2x   10x             15x 10x   10x 10x 10x   10x   15x   10x 7x                
import { useMemo } from "react";
 
type PinMode = "INPUT" | "OUTPUT" | "INPUT_PULLUP";
 
interface SketchAnalysisResult {
  analogPins: number[]; // concrete Arduino pin numbers (A0 -> 14)
  varMap: Record<string, number>;
  detectedPinModes: Record<number, PinMode>;
  pendingPinConflicts: number[]; // pins that are both used as analogRead and declared via pinMode
  digitalPinsFromPinMode: number[];
}
 
// ─── Atomic regex patterns (reduced complexity) ─────────────────────────────
 
/** Match "Ax" tokens (A0–A5). */
const A_PIN_RE = /^A(\d+)$/i;
 
/** Match numeric tokens (0–255). */
const NUMERIC_RE = /^\d+$/;
 
/** Match simple tokens (A\d, \d+, or alphanumeric). */
const SIMPLE_TOKEN_RE = /^(A\d+|\d+|\w+)$/i;
 
/** Match #define VAR Ax or #define VAR numeric. */
const DEFINE_PIN_RE = /#define\s+(\w+)\s+(A\d|\d+)/g;
 
/** Match int/const/uint8_t VAR = Ax or numeric assignment. */
const ASSIGN_PIN_RE = /(?:int|const\s+int|uint8_t|byte)\s+(\w+)\s*=\s*(A\d|\d+)\s*;/g;
 
/** Match analogRead(token) calls. */
const ANALOG_READ_RE = /analogRead\s*\(\s*([^)\s]+)\s*\)/g;
 
/** Extracts the body of a braced block starting at `openBracePos` in `src`. */
function extractBracedBody(src: string, openBracePos: number): string {
  let depth = 1, pos = openBracePos;
  while (pos < src.length && depth > 0) {
    if (src[pos] === '{') depth++;
    else if (src[pos] === '}') depth--;
    pos++;
  }
  return src.slice(openBracePos, pos - 1);
}
 
/** Match for-loop pattern with integer iteration (header + opening brace only; body extracted via brace counting). */
// Two separate regexes to avoid super-linear backtracking (S5843):
// 1. With type prefix:  for (int i = 0; i <= 5; ...)
const FOR_LOOP_TYPED_RE = /for *\( *\w+ +(\w+) *= *(\d+) *; *\w+ *(<=?) *(\d+) *;[^)]*\)/g;
// 2. Without type prefix: for (i = 0; i <= 5; ...)
const FOR_LOOP_BARE_RE = /for *\( *(\w+) *= *(\d+) *; *\w+ *(<=?) *(\d+) *;[^)]*\)/g;
// Verify the for-loop is followed by a brace
const FOR_BRACE_TAIL = /^ *\{/;
 
/** Match pinMode(pin, mode) calls. */
const PIN_MODE_RE = /pinMode\s*\(\s*(A\d+|\d+)\s*,\s*(INPUT_PULLUP|INPUT|OUTPUT)\s*\)/g;
 
// ─── Pin-token helpers ────────────────────────────────────────────────────────
 
/** Resolves an "Ax" token (e.g. "A2") to internal pin 14–19, or undefined. */
function resolveAPin(token: string): number | undefined {
  const m = A_PIN_RE.exec(token);
  if (!m) return undefined;
  const idx = Number(m[1]);
  return idx >= 0 && idx <= 5 ? 14 + idx : undefined;
}
 
/**
 * Resolves a numeric token for analogRead / define context:
 *   0–5   → mapped to 14–19
 *   14–19 → kept as-is
 *   otherwise → undefined
 */
function resolveNumericForAnalog(token: string): number | undefined {
  Iif (!NUMERIC_RE.test(token)) return undefined;
  const idx = Number(token);
  if (idx >= 0 && idx <= 5) return 14 + idx;
  Eif (idx >= 14 && idx <= 19) return idx;
  return undefined;
}
 
/** Resolves a define/assignment token ("A2" or numeric) to a pin number. */
function parsePinToken(token: string): number | undefined {
  return resolveAPin(token) ?? resolveNumericForAnalog(token);
}
 
/** Resolves an analogRead argument token to a pin number (includes varMap lookup). */
function resolveAnalogReadToken(
  tok: string,
  varMap: Map<string, number>,
): number | undefined {
  const aPin = resolveAPin(tok);
  if (aPin !== undefined) return aPin;
  if (NUMERIC_RE.test(tok)) return resolveNumericForAnalog(tok);
  return varMap.get(tok);
}
 
/**
 * Resolves a pinMode pin argument:
 *   "Ax" → 14+x (for x 0–5)
 *   numeric 0–255 → kept as-is
 */
function resolvePinModeToken(token: string): number | undefined {
  const aPin = resolveAPin(token);
  if (aPin !== undefined) return aPin;
  Eif (NUMERIC_RE.test(token)) {
    const idx = Number(token);
    Eif (idx >= 0 && idx <= 255) return idx;
  }
  return undefined;
}
 
/** Maps a raw modeToken string to a typed PinMode value. */
function resolvePinMode(modeToken: string): PinMode {
  if (modeToken === "INPUT_PULLUP") return "INPUT_PULLUP";
  Eif (modeToken === "OUTPUT") return "OUTPUT";
  return "INPUT";
}
 
// ─── Analysis passes ─────────────────────────────────────────────────────────
 
/** Extracts variable→pin mappings from #define macros and variable declarations. */
function extractVarMap(code: string): Map<string, number> {
  const varMap = new Map<string, number>();
 
  // #define VAR A0  or  #define VAR 0
  let m: RegExpExecArray | null = null;
  while ((m = DEFINE_PIN_RE.exec(code))) {
    const p = parsePinToken(m[2]);
    Eif (p !== undefined) varMap.set(m[1], p);
  }
 
  // int sensorPin = A0;  or  const int s = 0;
  while ((m = ASSIGN_PIN_RE.exec(code))) {
    const p = parsePinToken(m[2]);
    Eif (p !== undefined) varMap.set(m[1], p);
  }
 
  return varMap;
}
 
/** Finds all analog pins referenced via analogRead(...) calls. */
function findAnalogReadPins(
  code: string,
  varMap: Map<string, number>,
): Set<number> {
  const pins = new Set<number>();
  let m: RegExpExecArray | null = null;
 
  while ((m = ANALOG_READ_RE.exec(code))) {
    const token = m[1].trim();
    const simple = SIMPLE_TOKEN_RE.exec(token);
    Iif (!simple) continue;
    const pin = resolveAnalogReadToken(simple[1], varMap);
    Eif (pin !== undefined) pins.add(pin);
  }
  return pins;
}
 
/** Finds analog pins iterated in for-loops and used in analogRead. */
function findForLoopPins(code: string): Set<number> {
  const pins = new Set<number>();
 
  const processMatch = (fm: RegExpExecArray) => {
    const tail = code.slice(fm.index + fm[0].length);
    if (!FOR_BRACE_TAIL.test(tail)) return;
    const bracePos = fm.index + fm[0].length + tail.indexOf("{") + 1;
    const [, varName, startStr, cmp, endStr] = fm;
    const body = extractBracedBody(code, bracePos);
    const useRe = new RegExp(
      String.raw`analogRead\s*\(\s*${varName}\s*\)`,
      "g",
    );
    Iif (!useRe.test(body)) return;
    const start = Number(startStr);
    const last = cmp === "<=" ? Number(endStr) : Number(endStr) - 1;
    for (let pin = start; pin <= last; pin++) {
      if (pin >= 0 && pin <= 5) pins.add(14 + pinE);
      else if (pin >= 14 && pin <= 19) pins.add(pin);
    }
  };
 
  let fm: RegExpExecArray | null = null;
  while ((fm = FOR_LOOP_TYPED_RE.exec(code))) processMatch(fm);
  while ((fm = FOR_LOOP_BARE_RE.exec(code))) processMatch(fm);
 
  return pins;
}
 
interface PinModeResult {
  modes: Record<number, PinMode>;
  pins: Set<number>;
}
 
/** Finds all pins declared via pinMode(...) and their configured modes. */
function findPinModePins(code: string): PinModeResult {
  const modes: Record<number, PinMode> = {};
  const pins = new Set<number>();
  let m: RegExpExecArray | null = null;
 
  while ((m = PIN_MODE_RE.exec(code))) {
    const p = resolvePinModeToken(m[1]);
    Iif (p === undefined) continue;
    pins.add(p);
    modes[p] = resolvePinMode(m[2]);
  }
  return { modes, pins };
}
 
// ─── Hook ─────────────────────────────────────────────────────────────────────
 
// Hook: pure analysis of sketch source to detect pins, defines and pinMode(...) usage
export function useSketchAnalysis(code: string): SketchAnalysisResult {
  return useMemo(() => {
    const mainCode = code || "";
 
    const varMap = extractVarMap(mainCode);
    const pins = findAnalogReadPins(mainCode, varMap);
    for (const pin of findForLoopPins(mainCode)) pins.add(pin);
    const { modes: detectedModes, pins: pinModePins } =
      findPinModePins(mainCode);
 
    const overlap = Array.from(pins).filter((p) => pinModePins.has(p));
 
    return {
      analogPins: Array.from(pins).sort((a, b) => a - b),
      varMap: Object.fromEntries(varMap),
      detectedPinModes: detectedModes,
      pendingPinConflicts: overlap,
      digitalPinsFromPinMode: Array.from(pinModePins).sort((a, b) => a - b),
    };
  }, [code]);
}