All files / shared reserved-names-validator.ts

100% Statements 44/44
93.54% Branches 29/31
100% Functions 3/3
100% Lines 44/44

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  8x               8x                                                                                                                                                                                                                                                                                                                                                   72x     72x         72x     72x   72x 30x 30x 16x   16x   16x                           72x   72x 135x   135x         1x   1x   1x                       72x             72x 72x   72x   6403x   30x 700x   30x 29x 29x   6373x     4x   4x 186x 4x 4x   182x 7x   182x     6369x 6369x       72x                     17x 17x       8x  
import type { ParserMessage } from "./schema";
import { randomUUID } from "crypto";
 
type SeverityLevel = 1 | 2 | 3;
 
/**
 * Reserved names that conflict with standard C/C++ and Arduino libraries
 * These names cannot be used as variable/function names in Arduino sketches
 */
const RESERVED_STANDARD_NAMES = new Set([
  // POSIX functions (unistd.h, stdlib.h, etc.)
  "pause",
  "system",
  "abort",
  "exit",
  "signal",
  "fork",
  "exec",
  "execv",
  "execve",
  "execvp",
  "wait",
  "waitpid",
  "pipe",
  "dup",
  "dup2",
  "close",
  "read",
  "write",
  "open",
  "chmod",
  "chown",
  "getpid",
  "getppid",
  "getuid",
  "setuid",
  "getenv",
  "setenv",
  "putenv",
  "sleep",
  "usleep",
  "alarm",
  "time",
  "clock",
  "ctime",
  "localtime",
  "gmtime",
  "mktime",
  "strftime",
  "mkfifo",
  "rename",
  "remove",
  "mkdir",
  "rmdir",
  "getcwd",
  "chdir",
  "unlink",
  "truncate",
  "stat",
  "fstat",
  "lstat",
  "access",
  "link",
  "symlink",
  "readlink",
  "ftok",
  "getuid",
  "getgid",
  "getgroups",
  "setgroups",
  "setgid",
  "getlogin",
  "getpgrp",
  "setpgrp",
  "getpgid",
  "setpgid",
  "setsid",
  "tcgetpgrp",
  "tcsetpgrp",
  "ioctl",
  "fcntl",
  "flock",
 
  // stdio.h functions
  "printf",
  "fprintf",
  "sprintf",
  "snprintf",
  "scanf",
  "fscanf",
  "sscanf",
  "getchar",
  "putchar",
  "gets",
  "puts",
  "fopen",
  "freopen",
  "fclose",
  "fflush",
  "fgetc",
  "fputc",
  "fgets",
  "fputs",
  "fread",
  "fwrite",
  "fseek",
  "ftell",
  "rewind",
  "clearerr",
  "feof",
  "ferror",
  "perror",
 
  // stdlib.h functions
  "malloc",
  "calloc",
  "realloc",
  "free",
  "alloca",
  "atoi",
  "atol",
  "atof",
  "strtol",
  "strtoul",
  "strtof",
  "strtod",
  "rand",
  "srand",
  "qsort",
  "bsearch",
 
  // string.h functions
  "strlen",
  "strcpy",
  "strncpy",
  "strcat",
  "strncat",
  "strcmp",
  "strncmp",
  "strchr",
  "strrchr",
  "strstr",
  "memcpy",
  "memmove",
  "memset",
  "memchr",
  "memcmp",
  "strtok",
 
  // Arduino-specific conflicting names
  "setup",
  "loop",
  "Serial",
  "pinMode",
  "digitalWrite",
  "digitalRead",
  "analogWrite",
  "analogRead",
  "attachInterrupt",
  "detachInterrupt",
  "millis",
  "micros",
  "delay",
  "delayMicroseconds",
  "micros",
  "delayMicroseconds",
 
  // Common macros/constants
  "NULL",
  "EOF",
  "TRUE",
  "FALSE",
]);
 
class ReservedNamesValidator {
  /**
   * Validate Arduino code for reserved name conflicts
   */
  validateReservedNames(code: string): ParserMessage[] {
    const messages: ParserMessage[] = [];
 
    // Remove comments to check only active code
    const uncommentedCode = this.removeComments(code);
 
    // Check for variable declarations using reserved names
    // Match patterns like: int pause; float pause; int* pause; etc.
    const varDeclRegex =
      /\b(int|float|double|bool|byte|char|short|long|unsigned|void|const|volatile|static)\s+(?:\*+\s*)*(\w+)\s*(?:[=\[\;])/g;
 
    let match;
    const foundReservedNames = new Set<string>();
 
    while ((match = varDeclRegex.exec(uncommentedCode)) !== null) {
      const varName = match[2];
      if (RESERVED_STANDARD_NAMES.has(varName) && !foundReservedNames.has(varName)) {
        foundReservedNames.add(varName);
 
        const lineNum = this.findLineNumber(uncommentedCode, varName, match.index);
 
        messages.push({
          id: randomUUID(),
          type: "error",
          category: "reserved-name",
          severity: 3 as SeverityLevel,
          message: `Variable name "${varName}" conflicts with a standard library function and cannot be used.`,
          suggestion: `Rename the variable to something else (e.g., "${varName}Flag", "${varName}Value")`,
          line: lineNum,
        });
      }
    }
 
    // Also check for function definitions using reserved names
    const funcDeclRegex =
      /\b(?:int|float|double|bool|byte|char|short|long|unsigned|void)\s+(\w+)\s*\(/g;
 
    while ((match = funcDeclRegex.exec(uncommentedCode)) !== null) {
      const funcName = match[1];
      // Only warn about function names that are inside user code (not Arduino functions)
      if (
        RESERVED_STANDARD_NAMES.has(funcName) &&
        !["setup", "loop"].includes(funcName) &&
        !foundReservedNames.has(funcName)
      ) {
        foundReservedNames.add(funcName);
 
        const lineNum = this.findLineNumber(uncommentedCode, funcName, match.index);
 
        messages.push({
          id: randomUUID(),
          type: "error",
          category: "reserved-name",
          severity: 3 as SeverityLevel,
          message: `Function name "${funcName}" conflicts with a standard library function and cannot be used.`,
          suggestion: `Rename the function to something else (e.g., "${funcName}Custom", "${funcName}Handler")`,
          line: lineNum,
        });
      }
    }
 
    return messages;
  }
 
  /**
   * Remove C++ style comments from code
   */
  private removeComments(code: string): string {
    let result = "";
    let i = 0;
 
    while (i < code.length) {
      // Check for line comment //
      if (code[i] === "/" && code[i + 1] === "/") {
        // Skip until end of line
        while (i < code.length && code[i] !== "\n") {
          i++;
        }
        if (i < code.length) {
          result += "\n"; // Preserve newline
          i++;
        }
      }
      // Check for block comment /* */
      else if (code[i] === "/" && code[i + 1] === "*") {
        i += 2;
        // Skip until */
        while (i < code.length - 1) {
          if (code[i] === "*" && code[i + 1] === "/") {
            i += 2;
            break;
          }
          if (code[i] === "\n") {
            result += "\n"; // Preserve newlines to keep line numbers correct
          }
          i++;
        }
      } else {
        result += code[i];
        i++;
      }
    }
 
    return result;
  }
 
  /**
   * Find the line number where a name occurs
   */
  private findLineNumber(
    code: string,
    name: string,
    startIndex?: number,
  ): number {
    const searchCode = startIndex !== undefined ? code.substring(0, startIndex + name.length) : code.substring(0, code.indexOf(name) + name.length);
    return (searchCode.match(/\n/g) || []).length + 1;
  }
}
 
export const reservedNamesValidator = new ReservedNamesValidator();