All files / TRANSPILE/1-Analyze runAnalyzers.ts

98.5% Statements 66/67
87.5% Branches 7/8
98.18% Functions 54/55
100% Lines 66/66

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                                                                                                                                                                                                                                                                                                  23044x 23044x           51x               23044x                                                                       501x 501x 49x     501x 501x   501x                   501x       492x                 492x                 492x           490x       490x   1x       489x               489x       489x             487x           483x       480x       478x       477x                   469x       469x       468x         466x             466x         466x       466x         466x                                       466x         466x       466x       466x       466x               466x       466x       466x       466x       466x       464x       464x       464x       460x       460x           460x         460x       460x       460x       460x       460x       460x       460x       460x       458x       458x           451x 1x         501x 23044x                 23044x 50x       501x        
/**
 * Pass 2.1: every rejection C-Next makes about a parsed program.
 *
 * The steps run in the order declared below, and the loop STOPS at the first
 * non-advisory step that finds anything -- so a step's position is a decision
 * about which diagnostic a program with several faults is shown, not a detail.
 * Each entry carries a `label` saying why it sits where it does.
 *
 * The header used to say "All 14 analyzers (plus comment validation)", a count
 * carried verbatim from the pre-#1322 path and wrong by a factor of three by
 * the time it moved here. It is deliberately not replaced with a new number:
 * a literal in a comment beside the table it describes is the doc-rot this
 * card exists to remove, and `docs/error-codes.md` plus
 * `docs/architecture/throw-classification.md` carry the counts that ARE
 * gated.
 */
 
import { ProgramContext } from "../../PARSE/2-Parse/grammar/CNextParser";
import IComment from "../../types/IComment";
import CppClassInitializerAnalyzer from "./CppClassInitializerAnalyzer";
import DefineDirectiveAnalyzer from "./DefineDirectiveAnalyzer";
import IdentifierSyntaxAnalyzer from "./IdentifierSyntaxAnalyzer";
import LiteralFormAnalyzer from "./LiteralFormAnalyzer";
import ParameterNamingAnalyzer from "./ParameterNamingAnalyzer";
import StructFieldAnalyzer from "./StructFieldAnalyzer";
import TypeDeclarationAnalyzer from "./TypeDeclarationAnalyzer";
import InitializationAnalyzer from "./InitializationAnalyzer";
import FunctionCallAnalyzer from "./FunctionCallAnalyzer";
import UndeclaredTypeAnalyzer from "./UndeclaredTypeAnalyzer";
import UndeclaredValueAnalyzer from "./UndeclaredValueAnalyzer";
import NullCheckAnalyzer from "./NullCheckAnalyzer";
import DivisionByZeroAnalyzer from "./DivisionByZeroAnalyzer";
import FloatModuloAnalyzer from "./FloatModuloAnalyzer";
import ArrayIndexTypeAnalyzer from "./ArrayIndexTypeAnalyzer";
import ShiftAnalyzer from "./ShiftAnalyzer";
import BooleanOperandAnalyzer from "./BooleanOperandAnalyzer";
import MixedTypeCategoryAnalyzer from "./MixedTypeCategoryAnalyzer";
import ReturnPathAnalyzer from "./ReturnPathAnalyzer";
import ReturnValueUseAnalyzer from "./ReturnValueUseAnalyzer";
import CompoundAssignmentAnalyzer from "./CompoundAssignmentAnalyzer";
import ConstructorArgumentAnalyzer from "./ConstructorArgumentAnalyzer";
import CriticalSectionAnalyzer from "./CriticalSectionAnalyzer";
import EnumTypeSafetyAnalyzer from "./EnumTypeSafetyAnalyzer";
import ScopeAccessAnalyzer from "./ScopeAccessAnalyzer";
import RegisterAccessAnalyzer from "./RegisterAccessAnalyzer";
import BareEnumMemberAnalyzer from "./BareEnumMemberAnalyzer";
import ArrayDeclarationAnalyzer from "./ArrayDeclarationAnalyzer";
import ConstantDimensionAnalyzer from "./ConstantDimensionAnalyzer";
import ArrayIndexBoundsAnalyzer from "./ArrayIndexBoundsAnalyzer";
import CallbackAssignmentAnalyzer from "./CallbackAssignmentAnalyzer";
import BitmapAccessAnalyzer from "./BitmapAccessAnalyzer";
import SafeDivisionAnalyzer from "./SafeDivisionAnalyzer";
import BitAccessAnalyzer from "./BitAccessAnalyzer";
import DeclarationModifierAnalyzer from "./DeclarationModifierAnalyzer";
import SizeofAnalyzer from "./SizeofAnalyzer";
import StructLiteralAnalyzer from "./StructLiteralAnalyzer";
import ConstAssignmentAnalyzer from "./ConstAssignmentAnalyzer";
import LoopAnalyzer from "./LoopAnalyzer";
import SliceAssignmentAnalyzer from "./SliceAssignmentAnalyzer";
import ControllingExpressionAnalyzer from "./ControllingExpressionAnalyzer";
import IntegerConversionAnalyzer from "./IntegerConversionAnalyzer";
import LengthPropertyAnalyzer from "./LengthPropertyAnalyzer";
import StringDeclarationAnalyzer from "./StringDeclarationAnalyzer";
import SwitchStatementAnalyzer from "./SwitchStatementAnalyzer";
import NestedTernaryAnalyzer from "./NestedTernaryAnalyzer";
import ThisOutsideScopeAnalyzer from "./ThisOutsideScopeAnalyzer";
import CommentExtractor from "./CommentExtractor";
import ITranspileError from "../../lib/types/ITranspileError";
import IncludeDirectiveAnalyzer from "./IncludeDirectiveAnalyzer";
import IIncludeContext from "./types/IIncludeContext";
import type IAnalysisContext from "./types/IAnalysisContext";
 
/**
 * Options for running analyzers
 */
interface IAnalyzerOptions {
  /**
   * What 2.1 is allowed to know about the program -- see `IAnalysisContext`.
   *
   * REQUIRED, for the reason `includes` below gives at greater length: an
   * optional-with-a-fallback field is a guard that cannot fire. These facts
   * used to be read off `CodeGenState` at nineteen analyzer sites, for things
   * the caller is holding twenty lines above the call, and #1430 and #1432 are
   * what that costs once the shared answer is stale rather than redundant.
   */
  readonly context: IAnalysisContext;
 
  /**
   * #1672: 1.1 Discover's answers for this file's `#include` directives.
   * ADR-010's rules read them and ask the file system nothing, so the include
   * they accept and the file the run discovered cannot differ.
   *
   * #1322 passed the include facts in rather than reading them off shared
   * state, because the shared answer is WRONG at this moment:
   * `CodeGenState.sourcePath` was written inside `CodeGenerator.generate()`,
   * which runs after this -- the order-dependent-diagnostic shape #1399
   * shipped.
   *
   * REQUIRED, and that is the point. Optional-with-a-skip is a guard that
   * cannot fire: a caller who forgot it would lose all three ADR-010 rules
   * with nothing failing.
   */
  readonly includes: IIncludeContext;
 
  /**
   * #1322: whether this run emits C++.
   *
   * From `Transpiler.cppMode`, set once for the whole run, for the same reason
   * as `includes`: `CodeGenState.cppMode` is written inside
   * `CodeGenerator.generate()`. Measured at the first analyzer step, it is
   * `false` for a run's first file and holds the PREVIOUS file's value for
   * every file after -- so a rule copying codegen's guard would fire for files
   * 2..N and stay silent for file 1, which is worse than never firing because
   * it looks like it works.
   */
  readonly cppMode: boolean;
}
 
/**
 * Generic analyzer error with common fields.
 *
 * Deliberately WIDER than `IBaseAnalysisError`, not a copy of it: `code` is
 * optional and `rule` exists because this must also accept a step whose code is
 * not an `E` number. `helpText` is here for the opposite reason -- it was absent,
 * so every analyzer's suggested fix was silently discarded on the way through
 * (#1306). A field missing from an accepting type drops data without failing.
 */
interface IAnalyzerError {
  line: number;
  column: number;
  message: string;
  code?: string;
  rule?: string;
  helpText?: string;
}
 
/**
 * Convert analyzer errors to ITranspileError format and add to accumulator.
 * Returns true if any errors were added (for early return logic).
 */
function collectErrors(
  analyzerErrors: IAnalyzerError[],
  target: ITranspileError[],
  formatMessage?: (err: IAnalyzerError) => string,
): boolean {
  const formatter = formatMessage ?? ((e) => e.message);
  for (const err of analyzerErrors) {
    // #1306: `helpText` was set at 21 analyzer sites and read at none -- it was
    // dropped here, so the "Help" column in docs/error-codes.md documented output
    // that did not exist. Carrying it through moves 92 `.expected.error` files,
    // which is the evidence the advice now reaches a user rather than a cost to
    // route around.
    target.push({
      line: err.line,
      column: err.column,
      message: formatter(err),
      severity: "error",
      helpText: err.helpText,
    });
  }
  return analyzerErrors.length > 0;
}
 
/**
 * One analysis step.
 *
 * #1399 review: the body was fifteen repetitions of
 * `if (collectErrors(x.analyze(tree), errors, fmt)) return errors;`, which is a
 * table written as control flow -- cognitive complexity 16, over the 15 limit,
 * and growing by one with every analyzer added. The ordering constraints were
 * real but survived only as prose between the blocks; as entries they are data
 * that moves with the step.
 */
interface IAnalyzerStep {
  /** Why this step sits here, when its position matters. */
  readonly label: string;
  readonly run: () => IAnalyzerError[];
  /** Defaults to the `error[CODE]: message` form. */
  readonly format?: (err: IAnalyzerError) => string;
  /** When true, findings are reported and later steps still run. */
  readonly advisory?: boolean;
}
 
/**
 * Run all semantic analyzers on a parsed program.
 *
 * @param tree - The parsed program AST
 * @param comments - 1.2 Parse's comments, for MISRA 3.1/3.2 validation
 * @param options - Optional configuration including external struct info
 * @returns Array of errors (empty if all pass)
 */
function runAnalyzers(
  tree: ProgramContext,
  comments: readonly IComment[],
  options: IAnalyzerOptions,
): ITranspileError[] {
  const errors: ITranspileError[] = [];
  const formatWithCode = (e: IAnalyzerError) =>
    `error[${e.code}]: ${e.message}`;
 
  // #1456: the caller's, always. No fallback to shared state -- see the field.
  const context = options.context;
  const symbolTable = context.symbolTable;
 
  const steps: readonly IAnalyzerStep[] = [
    {
      // #1322: before anything reads a declaration. A file's directives
      // precede every declaration in the grammar, so a bad one is never a
      // consequence of the code below it -- and reporting the code below it
      // first would tell the author to fix the wrong line. Worse for includes
      // specifically: including the wrong file changes which names exist, so
      // every later step would be answering about a program the author did not
      // write.
      label: "#include targets (ADR-010: headers only, .cnx over .h)",
      run: () => new IncludeDirectiveAnalyzer().analyze(tree, options.includes),
    },
    {
      label: "#define shape (ADR-037: flag-only defines)",
      run: () => new DefineDirectiveAnalyzer().analyze(tree),
    },
    {
      // #1322: a C++ class initializer that has nowhere to put its
      // assignments. Reads only the run's mode and the symbol table, both
      // settled before this pass.
      label:
        "C++ class initializers (Issue #517: no statement position at file scope)",
      run: () =>
        new CppClassInitializerAnalyzer(context).analyze(
          tree,
          options.cppMode,
          symbolTable,
        ),
    },
    {
      // A malformed identifier feeds a bad name into every later analysis.
      label: "identifier syntax (ADR-063: no trailing or consecutive '_')",
      run: () => new IdentifierSyntaxAnalyzer().analyze(tree),
    },
    {
      // ADR-044: a malformed literal, like a malformed name, feeds every later
      // analysis -- a dimension or an enum value would report a consequence
      label: "integer literal form (ADR-044: no octal literal, E0912)",
      run: () => new LiteralFormAnalyzer().analyze(tree),
    },
    {
      label: "parameter naming (Issue #227: reserved naming patterns)",
      run: () => new ParameterNamingAnalyzer().analyze(tree),
      // Carries its own message text rather than a code.
      format: (e) => e.message,
    },
    {
      label: "struct fields (reserved field names like 'length')",
      run: () => new StructFieldAnalyzer().analyze(tree),
    },
    {
      // #1531: before anything reads a bitmap's fields or an enum's values.
      // A declaration whose own shape is wrong is the cause; a later step
      // reading it would report a consequence.
      label:
        "declared type shape (ADR-034 bitmap width E0893, ADR-017 enum values E0894, E0909-E0911)",
      run: () => new TypeDeclarationAnalyzer(context).analyze(),
    },
    {
      label: "initialization (Rust-style use-before-init)",
      run: () => new InitializationAnalyzer(context).analyze(tree, symbolTable),
    },
    {
      // Before the call and essential-type analyses: a type that denotes
      // nothing feeds an unknown type into every later question, so the
      // diagnostics after it would name a consequence rather than the cause.
      label: "undefined type references (#1312)",
      run: () => new UndeclaredTypeAnalyzer(context).analyze(tree),
    },
    {
      // After the type check, so a file whose type is undefined reports the
      // type rather than every use of it.
      label: "undefined value references (#1353)",
      run: () => new UndeclaredValueAnalyzer(context).analyze(tree),
    },
    {
      label: "call analysis (ADR-030: define-before-use)",
      run: () => new FunctionCallAnalyzer(context).analyze(tree, symbolTable),
    },
    {
      label: "NULL checks (ADR-047: C library interop)",
      run: () => new NullCheckAnalyzer().analyze(tree),
    },
    {
      label: "division by zero (ADR-051: compile-time detection)",
      run: () => new DivisionByZeroAnalyzer(context).analyze(tree),
    },
    {
      // #1175: before anything that reads a dimension's size -- a slice's
      // bounds (E0858), a count against it, a value's width -- since one with
      // no size is the cause, and those would report a consequence (#1863
      // review). After E0427 and E0800, which own an undeclared bare name and
      // a literal or const divisor of zero.
      label:
        "constant array dimensions (ADR-023 no VLAs, ADR-044, E0909/E0910)",
      run: () => new ConstantDimensionAnalyzer(context).analyze(tree),
    },
    {
      label: "float modulo (% with f32/f64)",
      run: () => new FloatModuloAnalyzer(context).analyze(tree),
    },
    {
      label: "array index type (ADR-054: unsigned indexes only)",
      run: () => new ArrayIndexTypeAnalyzer(context).analyze(tree),
    },
    {
      label:
        "shift operands and amounts (MISRA C:2012 Rules 10.1 and 12.2, E0805/E0873)",
      run: () => new ShiftAnalyzer(context).analyze(tree),
    },
    {
      // Before the Rule 10.4 check, so a bool in an arithmetic expression is
      // reported as "not a number" rather than as a category mismatch with
      // whatever it was combined with.
      label: "boolean operands (MISRA C:2012 Rule 10.1, Issue #1183)",
      run: () => new BooleanOperandAnalyzer(context).analyze(tree),
    },
    {
      label:
        "mixed essential type category (MISRA C:2012 Rule 10.4, ADR-024 / Issue #1091)",
      run: () => new MixedTypeCategoryAnalyzer(context).analyze(tree),
    },
    {
      label: "return paths (ADR-067: non-void must return on all paths)",
      run: () => new ReturnPathAnalyzer().analyze(tree),
    },
    {
      label:
        "return-value use (ADR-070 / MISRA C:2012 Rule 17.7 at source level)",
      run: () => ReturnValueUseAnalyzer.analyze(tree, symbolTable, context),
    },
    // ---------------------------------------------------------------------
    // #1322 relocations: appended as a BLOCK, never inserted among the steps
    // above. The loop breaks at the first non-advisory step that finds
    // anything, so where a step sits decides which diagnostic a file reports
    // when two would fire. Appending is the only placement that CANNOT change
    // what an existing fixture says -- every file that reaches an older
    // analyzer today still reaches it first -- and a fixture that quietly
    // starts reporting a different code is what
    // `diagnostics:manifest:check` calls `code-removed`, which the suite
    // stays green through.
    //
    // Order WITHIN this block is not load-bearing: no fixture triggers two of
    // these rules, so no diagnostic depends on it. A later relocation that
    // needs to preempt a step ABOVE the block states its
    // cause-before-consequence reason at its own entry, as the pairs above do.
    // ---------------------------------------------------------------------
    {
      label: "nested ternary in a condition or branch (ADR-022, E0710)",
      run: () => new NestedTernaryAnalyzer().analyze(tree),
    },
    {
      label:
        "compound assignment needs a whole storage location (ADR-007, E0857)",
      run: () => new CompoundAssignmentAnalyzer(context).analyze(tree),
    },
    {
      label: "C++ constructor arguments must be declared const (ADR-013, #375)",
      run: () => new ConstructorArgumentAnalyzer(context).analyze(tree),
    },
    {
      label: "`return` inside a critical section (ADR-050, E0853)",
      run: () => new CriticalSectionAnalyzer().analyze(tree),
    },
    {
      label: "`this` outside a scope (ADR-016)",
      run: () => new ThisOutsideScopeAnalyzer().analyze(tree),
    },
    {
      // Before the enum type-safety step: `Color c <- YELLOW` with YELLOW
      // declared by another enum is a bare member in the wrong place, and
      // "did you mean 'Status.YELLOW'" is the useful answer; the type-safety
      // step would call the same line a non-enum value.
      label: "bare enum members (ADR-017, E0424)",
      run: () => new BareEnumMemberAnalyzer(context).analyze(tree),
    },
    {
      label: "enum type safety (ADR-017, E0428/E0434)",
      run: () => new EnumTypeSafetyAnalyzer(context).analyze(tree),
    },
    {
      label: "slice assignment (ADR-007, E0858-E0861)",
      run: () => new SliceAssignmentAnalyzer(context).analyze(tree),
    },
    {
      label: "switch statements (ADR-025, E0711-E0714)",
      run: () => new SwitchStatementAnalyzer(context).analyze(tree),
    },
    {
      label: "controlling expressions (ADR-022, MISRA 14.4/13.5, E0701/E0702)",
      run: () => new ControllingExpressionAnalyzer(context).analyze(tree),
    },
    {
      label: "string declarations (ADR-045, E0862-E0866)",
      run: () => new StringDeclarationAnalyzer(context).analyze(tree),
    },
    {
      label: "length properties (ADR-058, E0867)",
      run: () => new LengthPropertyAnalyzer(context).analyze(tree),
    },
    {
      label: "integer conversions (ADR-024, E0868/E0869)",
      run: () => new IntegerConversionAnalyzer(context).analyze(tree),
    },
    {
      label: "scope access (ADR-016, E0435-E0437)",
      run: () => new ScopeAccessAnalyzer(context).analyze(tree),
    },
    {
      label: "register access modifiers (ADR-004, E0870-E0872)",
      run: () => new RegisterAccessAnalyzer(context).analyze(tree),
    },
    {
      // After controlling expressions: the always-true check assumes E0701
      // already guaranteed a comparison, as it did in codegen.
      label: "loops and break/continue (ADR-068/ADR-026, E0703/E0705/E0707)",
      run: () => new LoopAnalyzer().analyze(tree),
    },
    {
      label:
        "array declarations and initializers (ADR-035/036, E0866/E0874-E0876/E0892)",
      run: () => new ArrayDeclarationAnalyzer(context).analyze(tree),
    },
    {
      label: "constant array index bounds (ADR-036, E0854)",
      run: () => new ArrayIndexBoundsAnalyzer(context).analyze(tree),
    },
    {
      label: "const enforcement (ADR-013, E0877/E0878)",
      run: () => new ConstAssignmentAnalyzer(context).analyze(tree),
    },
    {
      label: "callback typing (ADR-029, E0879/E0880)",
      run: () => new CallbackAssignmentAnalyzer(context).analyze(tree),
    },
    {
      label: "struct initializers (ADR-014, E0357/E0358)",
      run: () => new StructLiteralAnalyzer(context).analyze(tree),
    },
    {
      label: "bitmap access (ADR-034, E0881-E0883)",
      run: () => new BitmapAccessAnalyzer(context).analyze(tree),
    },
    {
      label: "safe_div/safe_mod call shape (ADR-051, E0884/E0885)",
      run: () => new SafeDivisionAnalyzer(context).analyze(tree),
    },
    {
      label: "sizeof operands (ADR-023, E0601/E0602)",
      run: () => new SizeofAnalyzer().analyze(tree),
    },
    {
      label: "declaration modifiers (ADR-049, E0889)",
      run: () => new DeclarationModifierAnalyzer().analyze(tree),
    },
    {
      label: "bit indexing depth and scope (ADR-007/036, E0856/E0888)",
      run: () => new BitAccessAnalyzer(context).analyze(tree),
    },
    {
      // Last, and does not halt: comment findings are reported alongside
      // whatever else the file produced.
      label: "comment validation (MISRA C:2012 Rules 3.1, 3.2 -- ADR-043)",
      run: () => new CommentExtractor(comments).validate(),
      format: (e) => `error[MISRA-${e.rule}]: ${e.message}`,
      advisory: true,
    },
  ];
 
  for (const step of steps) {
    const found = collectErrors(
      step.run(),
      errors,
      step.format ?? formatWithCode,
    );
    // `break`, not an early `return`: both exits hand back the same `errors`
    // array, so returning from inside the loop reads as two exits with one
    // value (S3516) when it is really one exit and a stopping condition. What
    // varies is what `errors` CONTAINS, which no return statement expresses.
    if (found && !step.advisory) {
      break;
    }
  }
 
  return errors;
}
 
export default runAnalyzers;