All files walk.ts

96.67% Statements 494/511
89.67% Branches 139/155
96.96% Functions 32/33
96.67% Lines 494/511

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 7501x                                                                                                                                       1x 1x 1x       1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x   1x 53x       53x 53x 53x   53x   53x 64x 64x 64x 64x 64x           64x   53x 53x   64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x   64x 64x 64x 64x 64x 64x 64x 64x           64x   64x 64x 64x 64x 64x 64x 64x 64x 64x 64x   64x 64x                                                                                     64x 64x 64x 64x 64x 64x 153x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 64x   19x     19x 19x 57x 57x 2x 2x 2x 57x     19x 19x 19x 21x 19x 21x 2x 2x 21x   19x 19x 19x                                 1596x 1596x 72x 72x 72x 1596x 55x 55x 55x 1596x 10x 10x 10x 1596x 4x 4x 1596x 17x 17x 17x 17x 17x 17x 17x 1596x 1455x   72x 72x     72x 72x 72x   65x 65x 65x 65x 65x 65x 65x 65x 65x 65x 65x 65x 65x 65x 65x   4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x   65x 65x 65x 65x 65x 65x 65x 65x 65x 65x 65x 65x 65x   65x 65x 65x 65x 65x 65x 65x 65x 65x 65x 65x 65x 65x 65x 65x 65x 65x 65x 65x 65x 65x   4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x   64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x 64x       137x 137x 137x 137x   133x 133x       2x 2x   64x 64x 64x   63x 63x 63x   64x 1x 1x                 130x 130x 416x 416x 102x 102x   65x           65x 65x 14x 16x 14x 16x 5x 56x 56x   65x 65x 65x 65x 41x 18x 2x 2x 18x 14x 14x   63x 63x   2x 2x 2x 2x 61x 61x   65x 65x 65x 65x 65x 65x 65x 12x 12x 12x 11x 11x 11x 11x 11x 11x 12x 65x 65x   4x 4x 4x         4x 4x 4x 3x 3x 1x 1x 1x 2x 2x 1x 1x               1x 1x 2x 2x     1x                 133x 133x 133x 133x   1x               133x 133x 133x 133x 7223x 7223x       7223x 1x 1x 1x     7223x 4x 4x 4x 4x 4x 7218x 7223x 4x 4x 4x 4x 4x 7223x 4x 4x 4x 4x 4x 7210x 7210x 7210x 133x 133x               1x   1x 1x 11x 10x 10x         4x 4x 4x 4x 4x 4x 4x 64x 2x 2x 2x 2x 64x 4x 4x 4x 4x     58x 58x 58x 4x 4x   4x 4x 4x 4x   4x 4x 4x 118x 4x 4x 4x 4x 118x 4x 4x 4x 4x 110x 110x 110x 4x 4x   4x 4x 4x 4x 4x 4x 4x 4x 10x 10x 2x 2x 2x 2x 2x 10x 2x 2x 2x 2x 2x 10x 4x 4x 4x 4x     2x 2x 2x 4x 4x   133x 133x 133x   133x 133x 133x       133x 133x 133x 129x 133x   1x 64x 64x   64x 64x 64x  
/**
 * Java walkProject — emit FunctionOccurrences + CallSiteRecords.
 *
 * Identifies the callable shapes:
 *
 *   - `method_declaration` inside a type body          → 'method'
 *     - `enclosingClass` = immediate enclosing
 *       class/interface/record/enum/annotation_type name.
 *   - `constructor_declaration`                        → 'constructor'
 *   - `lambda_expression`                              → 'arrow'
 *   - one synthetic `<module-init>` per file owning the file's
 *     top-level structure (package, imports, type declarations).
 *
 * Note: Java doesn't have free-standing top-level functions. All
 * methods live inside a type. The `'function-declaration'` kind is
 * unused for Java; methods at any depth get kind='method' (or
 * 'constructor' for ctor declarations).
 *
 * Body hashing: sha256 of normalized body text. Normalization:
 *   1. Strip line comments (`// …` to end-of-line).
 *   2. Strip block comments (`/* … *\/`). Java block comments do NOT
 *      nest (unlike Rust).
 *   3. Strip Javadoc comments — they're a `/**` subset of block
 *      comments and the same scanner handles them.
 *   4. Preserve string literals: both regular `"…"` and text blocks
 *      `"""…"""` (Java 15+). Their content is part of behavior.
 *   5. Preserve char literals (`'x'`, `'\n'`).
 *   6. Collapse whitespace.
 *
 * Call-site records:
 *   - `method_invocation`            — `foo(...)`, `obj.foo(...)`,
 *                                       `Class.foo(...)`, `this.foo(...)`,
 *                                       `super.foo(...)`.
 *   - `object_creation_expression`   — `new Foo(...)` invokes the
 *                                       constructor; resolver treats
 *                                       the type name as the target.
 *   - `explicit_constructor_invocation` — `super(...)` / `this(...)`
 *                                       inside a constructor body.
 *   - 'creation' edges for `lambda_expression` — reachability flows
 *     through closures even when their dispatch is unresolvable.
 *   - `method_reference` (`Foo::bar`) is NOT recorded — it creates a
 *     callable handle but doesn't invoke. Skipping avoids inflating
 *     the graph with edges that never fire at that source location.
 *
 * Test detection (file-level):
 *   - Path contains `/test/` (catches Maven/Gradle `src/test/java/`).
 *   - Filename ends with `Test.java`, `Tests.java`, or `IT.java`.
 *
 * Test detection (function-level):
 *   - Methods annotated `@Test` (JUnit 4/5) are tagged `inTestFile`
 *     even when the file path doesn't match. Inline test methods
 *     are a common pattern; this honors them.
 */
 
import { createHash } from 'node:crypto';
import { relative, sep } from 'node:path';
 
import type { JavaParsedFile, JavaParsedProject } from './parse.js';
import type {
  CallSiteRecord,
  DependencySiteRecord,
  FunctionOccurrence,
  ParseError,
  WalkInput,
  WalkOutput,
} from '@opensip-tools/graph';
import type Parser from 'tree-sitter';
 
const TEST_PATH_RE = /(?:^|\/)test\//;
const TEST_FILE_NAME_RE = /(?:^|\/)[^/]*(?:Test|Tests|IT)\.java$/;
const GENERATED_PATH_RE = /(?:\b(?:target|build|out|generated|generated-sources)\/)|(?:\$Pb\.java$)/;
 
// Type declarations that introduce an enclosing-class context for the
// methods/constructors inside them.
const TYPE_DECL_NODES: ReadonlySet<string> = new Set([
  'class_declaration',
  'interface_declaration',
  'record_declaration',
  'enum_declaration',
  'annotation_type_declaration',
]);
 
// Call-site node kinds that the walk surfaces as 'call' records.
const CALL_NODES: ReadonlySet<string> = new Set([
  'method_invocation',
  'object_creation_expression',
  'explicit_constructor_invocation',
]);
 
export function walkProject(input: WalkInput<JavaParsedProject>): WalkOutput {
  const occurrences: Record<string, FunctionOccurrence[]> = Object.create(null) as Record<
    string,
    FunctionOccurrence[]
  >;
  const callSites: CallSiteRecord[] = [];
  const dependencySites: DependencySiteRecord[] = [];
  const parseErrors: ParseError[] = [];
 
  const sortedPaths = [...input.files].filter((p) => input.project.files.has(p)).sort();
 
  for (const path of sortedPaths) {
    const file = input.project.files.get(path);
    if (!file) continue;
    try {
      walkFile(path, file, input.projectDirAbs, occurrences, callSites, dependencySites);
    } catch (error) {
      parseErrors.push({
        filePath: relative(input.projectDirAbs, path),
        message: error instanceof Error ? error.message : String(error),
      });
    }
  }
 
  return { occurrences, callSites, dependencySites, parseErrors };
}
 
function walkFile(
  absPath: string,
  file: JavaParsedFile,
  projectDirAbs: string,
  out: Record<string, FunctionOccurrence[]>,
  callSites: CallSiteRecord[],
  dependencySites: DependencySiteRecord[],
): void {
  const filePathProjectRel = relative(projectDirAbs, absPath).split(sep).join('/');
  const inTestFile = isTestFile(filePathProjectRel);
  const definedInGenerated = isGeneratedFile(filePathProjectRel);
  const packageName = extractPackageName(file);
 
  const moduleInit = synthesizeModuleInit(
    file,
    filePathProjectRel,
    packageName,
    inTestFile,
    definedInGenerated,
  );
  record(out, moduleInit);
 
  // Phase 4 (DEC-498): walk top-level `import` declarations as dependency
  // sites. Owner is the file's synthesized module-init occurrence.
  // Implicit `java.lang.*` and same-package imports are NOT synthesized —
  // only explicit `import_declaration` nodes are emitted.
  collectDependencySites(file, moduleInit.bodyHash, dependencySites);
 
  const ctx: WalkCtx = {
    file,
    filePathProjectRel,
    packageName,
    fileInTestFile: inTestFile,
    definedInGenerated,
    out,
    callSites,
  };
  const initialFrame: Frame = { ownerHash: moduleInit.bodyHash, enclosingClass: null };
 
  for (const child of file.tree.rootNode.children) visit(child, initialFrame, ctx);
}
 
/**
 * Walk a Java file's top-level `import_declaration` nodes; emit one
 * `DependencySiteRecord` per import statement. Phase 4 of opensip's
 * substrate consolidation (DEC-498).
 *
 * Tree-sitter-java's `import_declaration` shape (from probe):
 *
 *   - Type import — `import com.example.foo.Bar;`
 *       children: ['import' kw, scoped_identifier 'com.example.foo.Bar', ';']
 *       specifier: `'com.example.foo.Bar'`
 *
 *   - Wildcard — `import com.example.foo.*;`
 *       children: ['import' kw, scoped_identifier 'com.example.foo',
 *                  '.' anon, asterisk '*', ';']
 *       specifier: `'com.example.foo.*'`
 *
 *   - Static type — `import static com.example.foo.Bar.method;`
 *       children: ['import' kw, 'static' kw, scoped_identifier
 *                  'com.example.foo.Bar.method', ';']
 *       specifier: `'static com.example.foo.Bar.method'`
 *
 *   - Static wildcard — `import static com.example.foo.Bar.*;`
 *       children: ['import' kw, 'static' kw, scoped_identifier
 *                  'com.example.foo.Bar', '.' anon, asterisk '*', ';']
 *       specifier: `'static com.example.foo.Bar.*'`
 *
 * We detect `static` by scanning the anonymous (non-named) children for
 * a token whose type is `'static'`, and detect the wildcard by checking
 * for a named `asterisk` child. The dotted path is the single named
 * `scoped_identifier` (or bare `identifier` in the degenerate
 * `import Foo;` default-package case) child.
 *
 * Out of scope at v1:
 *   - `module-info.java` `requires` directives (Java 9+ Java Platform
 *     Module System) — declarative module deps live there, not here.
 *   - Implicit `java.lang.*` imports — every Java file imports these,
 *     but we don't synthesize edges for non-explicit imports.
 *   - Implicit same-package visibility — Java doesn't require imports
 *     for sibling types in the same package; we likewise don't
 *     synthesize them.
 */
function collectDependencySites(
  file: JavaParsedFile,
  moduleInitHash: string,
  out: DependencySiteRecord[],
): void {
  for (const stmt of file.tree.rootNode.namedChildren) {
    if (stmt.type !== 'import_declaration') continue;
    const specifier = decodeImportSpecifier(stmt);
    if (specifier === null) continue;
    out.push({
      nodeRef: stmt,
      sourceFileRef: file,
      ownerHash: moduleInitHash,
      specifier,
      line: stmt.startPosition.row + 1,
      column: stmt.startPosition.column,
    });
  }
}
 
function decodeImportSpecifier(decl: Parser.SyntaxNode): string | null {
  // `static` is an anonymous keyword child; scan all children (named +
  // anonymous) for it.
  let isStatic = false;
  for (let i = 0; i < decl.childCount; i++) {
    const c = decl.child(i);
    if (c?.type === 'static') {
      isStatic = true;
      break;
    }
  }
  // Named children hold the path (scoped_identifier or identifier) and
  // the optional `asterisk` wildcard. Scan in order.
  let path: string | null = null;
  let wildcard = false;
  for (const c of decl.namedChildren) {
    if (c.type === 'scoped_identifier' || c.type === 'identifier') {
      path = c.text;
    } else if (c.type === 'asterisk') {
      wildcard = true;
    }
  }
  if (path === null) /* v8 ignore next */ return null;
  const tail = wildcard ? `${path}.*` : path;
  return isStatic ? `static ${tail}` : tail;
}
 
interface Frame {
  readonly ownerHash: string;
  readonly enclosingClass: string | null;
}
 
interface WalkCtx {
  readonly file: JavaParsedFile;
  readonly filePathProjectRel: string;
  readonly packageName: string;
  readonly fileInTestFile: boolean;
  readonly definedInGenerated: boolean;
  readonly out: Record<string, FunctionOccurrence[]>;
  readonly callSites: CallSiteRecord[];
}
 
function visit(node: Parser.SyntaxNode, frame: Frame, ctx: WalkCtx): void {
  if (TYPE_DECL_NODES.has(node.type)) {
    visitTypeDeclaration(node, frame, ctx);
    return;
  }
  if (node.type === 'method_declaration') {
    visitMethodOrConstructor(node, frame, ctx, 'method');
    return;
  }
  if (node.type === 'constructor_declaration') {
    visitMethodOrConstructor(node, frame, ctx, 'constructor');
    return;
  }
  if (node.type === 'lambda_expression' && visitLambda(node, frame, ctx)) {
    return;
  }
  if (CALL_NODES.has(node.type)) {
    ctx.callSites.push({
      nodeRef: node,
      sourceFileRef: ctx.file,
      ownerHash: frame.ownerHash,
      kind: 'call',
    });
  }
  for (const child of node.children) visit(child, frame, ctx);
}
 
function visitTypeDeclaration(node: Parser.SyntaxNode, frame: Frame, ctx: WalkCtx): void {
  const typeName = nameOf(node) ?? '<anon-type>';
  // Type declarations don't emit a function — their bodies' methods do.
  // Keep the same owner hash but update enclosingClass for children.
  const childFrame: Frame = { ownerHash: frame.ownerHash, enclosingClass: typeName };
  for (const child of node.children) visit(child, childFrame, ctx);
}
 
function visitMethodOrConstructor(
  node: Parser.SyntaxNode,
  frame: Frame,
  ctx: WalkCtx,
  kind: 'method' | 'constructor',
): void {
  const occ = buildMethodOccurrence(node, frame, ctx, kind);
  if (!occ) return;
  record(ctx.out, occ);
  const childFrame: Frame = { ownerHash: occ.bodyHash, enclosingClass: null };
  const body = node.childForFieldName('body');
  if (body) {
    for (const child of body.children) visit(child, childFrame, ctx);
  }
}
 
function visitLambda(node: Parser.SyntaxNode, frame: Frame, ctx: WalkCtx): boolean {
  const occ = buildLambdaOccurrence(node, ctx);
  if (!occ) return false;
  record(ctx.out, occ);
  if (frame.ownerHash !== occ.bodyHash) {
    ctx.callSites.push({
      nodeRef: node,
      sourceFileRef: ctx.file,
      ownerHash: frame.ownerHash,
      kind: 'creation',
      childHash: occ.bodyHash,
    });
  }
  const body = node.childForFieldName('body');
  if (body) {
    visit(body, { ownerHash: occ.bodyHash, enclosingClass: null }, ctx);
  }
  return true;
}
 
function buildMethodOccurrence(
  node: Parser.SyntaxNode,
  frame: Frame,
  ctx: WalkCtx,
  kind: 'method' | 'constructor',
): FunctionOccurrence | null {
  const name = nameOf(node) ?? '<anon-fn>';
  const digest = digestJavaBody(ctx.file.source.slice(node.startIndex, node.endIndex));
  const decorators = extractAnnotations(node);
  const inTest = ctx.fileInTestFile || hasTestAnnotation(decorators);
  const visibility = classifyVisibility(node);
  const qualifiedBase = packageQualifier(ctx.packageName, ctx.filePathProjectRel);
  const qualifiedName = frame.enclosingClass === null
    ? `${qualifiedBase}.${name}`
    : `${qualifiedBase}.${frame.enclosingClass}.${name}`;
  return {
    bodyHash: digest.hash,
    bodySize: digest.size,
    simpleName: name,
    qualifiedName,
    filePath: ctx.filePathProjectRel,
    line: node.startPosition.row + 1,
    column: node.startPosition.column,
    endLine: node.endPosition.row + 1,
    kind,
    params: extractParams(node),
    returnType: null,
    enclosingClass: frame.enclosingClass,
    decorators,
    visibility,
    inTestFile: inTest,
    definedInGenerated: ctx.definedInGenerated,
    calls: [],
  };
}
 
function buildLambdaOccurrence(
  node: Parser.SyntaxNode,
  ctx: WalkCtx,
): FunctionOccurrence | null {
  const digest = digestJavaBody(ctx.file.source.slice(node.startIndex, node.endIndex));
  const startLine = node.startPosition.row + 1;
  const startCol = node.startPosition.column;
  const simpleName = `<arrow:${ctx.filePathProjectRel}:${String(startLine)}:${String(startCol)}>`;
  const qualifiedBase = packageQualifier(ctx.packageName, ctx.filePathProjectRel);
  return {
    bodyHash: digest.hash,
    bodySize: digest.size,
    simpleName,
    qualifiedName: `${qualifiedBase}.<lambda:${String(startLine)}:${String(startCol)}>`,
    filePath: ctx.filePathProjectRel,
    line: startLine,
    column: startCol,
    endLine: node.endPosition.row + 1,
    kind: 'arrow',
    params: extractLambdaParams(node),
    returnType: null,
    enclosingClass: null,
    decorators: [],
    visibility: 'private',
    inTestFile: ctx.fileInTestFile,
    definedInGenerated: ctx.definedInGenerated,
    calls: [],
  };
}
 
function synthesizeModuleInit(
  file: JavaParsedFile,
  filePathProjectRel: string,
  packageName: string,
  inTestFile: boolean,
  definedInGenerated: boolean,
): FunctionOccurrence {
  const root = file.tree.rootNode;
  const topLevelText = root.children
    .map((c) => file.source.slice(c.startIndex, c.endIndex))
    .join('\n');
  const digest = digestSyntheticBody(`${filePathProjectRel}\n${topLevelText}`);
  const simpleName = `<module-init:${filePathProjectRel}>`;
  const qualifiedBase = packageQualifier(packageName, filePathProjectRel);
  return {
    bodyHash: digest.hash,
    bodySize: digest.size,
    simpleName,
    qualifiedName: `${qualifiedBase}.<module-init>`,
    filePath: filePathProjectRel,
    line: 1,
    column: 0,
    endLine: root.endPosition.row + 1,
    kind: 'module-init',
    params: [],
    returnType: null,
    enclosingClass: null,
    decorators: [],
    visibility: 'module-local',
    inTestFile,
    definedInGenerated,
    calls: [],
  };
}
 
// ── helpers ───────────────────────────────────────────────────────
 
function nameOf(node: Parser.SyntaxNode): string | null {
  const name = node.childForFieldName('name');
  return name ? name.text : null;
}
 
function packageQualifier(packageName: string, filePathProjectRel: string): string {
  if (packageName.length > 0) return packageName;
  // Fallback: derive a path-based qualifier (e.g. `src/main/java/Foo.java` →
  // `src.main.java.Foo`). Real Java files almost always have a `package`
  // declaration, so this is only hit for hand-written one-off files.
  return filePathProjectRel.replace(/\.java$/, '').replaceAll('/', '.');
}
 
function extractPackageName(file: JavaParsedFile): string {
  for (const child of file.tree.rootNode.children) {
    if (child.type === 'package_declaration') {
      // package_declaration: `package` keyword + scoped/qualified identifier + `;`
      for (const c of child.namedChildren) {
        if (c.type === 'scoped_identifier' || c.type === 'identifier') return c.text;
      }
    }
  }
  return '';
}
 
/**
 * Find the `modifiers` named child of a method/constructor declaration.
 *
 * Note: tree-sitter-java exposes the modifier list as a named child of
 * type `modifiers`, NOT as a named field. `childForFieldName('modifiers')`
 * returns null — only iteration works.
 */
function findModifiersNode(node: Parser.SyntaxNode): Parser.SyntaxNode | null {
  for (const c of node.children) {
    if (c.type === 'modifiers') return c;
  }
  return null;
}
 
function classifyVisibility(node: Parser.SyntaxNode): FunctionOccurrence['visibility'] {
  // Visibility keywords appear inside the `modifiers` node as anonymous
  // children with type === 'public' / 'protected' / 'private'.
  //   public / protected  → 'exported'
  //   private             → 'module-local' (file-local in Java terms)
  //   none                → 'module-local' (package-private)
  const modifiers = findModifiersNode(node);
  if (modifiers) {
    for (const c of modifiers.children) {
      if (c.type === 'public' || c.type === 'protected') return 'exported';
      if (c.type === 'private') return 'module-local';
    }
  }
  return 'module-local';
}
 
function extractAnnotations(node: Parser.SyntaxNode): readonly string[] {
  const out: string[] = [];
  const modifiers = findModifiersNode(node);
  if (!modifiers) return out;
  for (const c of modifiers.children) {
    if (c.type === 'annotation' || c.type === 'marker_annotation') {
      out.push(c.text.trim());
    }
  }
  return out;
}
 
function hasTestAnnotation(decorators: readonly string[]): boolean {
  for (const d of decorators) {
    // Matches `@Test`, `@org.junit.Test`, `@ParameterizedTest`, etc.
    if (/@(?:[\w.]*\.)?(?:Test|ParameterizedTest|RepeatedTest|TestFactory|TestTemplate)\b/.test(d)) {
      return true;
    }
  }
  return false;
}
 
function extractParams(
  node: Parser.SyntaxNode,
): readonly { name: string; optional: boolean; rest: boolean }[] {
  const params = node.childForFieldName('parameters');
  if (!params) return [];
  const out: { name: string; optional: boolean; rest: boolean }[] = [];
  for (const child of params.namedChildren) {
    if (child.type === 'formal_parameter' || child.type === 'spread_parameter') {
      const nameNode = child.childForFieldName('name') ?? findIdentifierChild(child);
      if (!nameNode) continue;
      out.push({
        name: nameNode.text,
        optional: false,
        rest: child.type === 'spread_parameter',
      });
    }
  }
  return out;
}
 
function extractLambdaParams(
  node: Parser.SyntaxNode,
): readonly { name: string; optional: boolean; rest: boolean }[] {
  // tree-sitter-java's lambda_expression `parameters` can be:
  //   - identifier               — `x -> x + 1`
  //   - formal_parameters        — `(int x) -> x + 1`
  //   - inferred_parameters      — `(x, y) -> x + y`
  const params = node.childForFieldName('parameters');
  if (!params) return [];
  if (params.type === 'identifier') {
    return [{ name: params.text, optional: false, rest: false }];
  }
  if (params.type === 'inferred_parameters') {
    const out: { name: string; optional: boolean; rest: boolean }[] = [];
    for (const c of params.namedChildren) {
      if (c.type === 'identifier') out.push({ name: c.text, optional: false, rest: false });
    }
    return out;
  }
  // formal_parameters falls through to the standard extractor.
  /* v8 ignore start */
  if (params.type === 'formal_parameters') return extractParams(node);
  return [];
  /* v8 ignore stop */
}
 
function findIdentifierChild(node: Parser.SyntaxNode): Parser.SyntaxNode | null {
  for (const c of node.namedChildren) {
    if (c.type === 'identifier') return c;
  }
  /* v8 ignore next */
  return null;
}
 
// ── body normalization ────────────────────────────────────────────
 
interface BodyDigest {
  readonly hash: string;
  readonly size: number;
}
 
function digestJavaBody(text: string): BodyDigest {
  const normalized = normalizeWhitespace(stripJavaComments(text));
  return { hash: sha256(normalized), size: normalized.length };
}
 
const digestSyntheticBody = digestJavaBody;
 
/**
 * Strip Java `//` line comments and `/* … *\/` block comments (which
 * include Javadoc `/** … *\/` — same scanner). Java block comments do
 * NOT nest. Preserve string literals (regular `"…"` and text blocks
 * `"""…"""`) and char literals.
 */
function stripJavaComments(text: string): string {
  let out = '';
  let i = 0;
  while (i < text.length) {
    const next2 = text.slice(i, i + 2);
    if (next2 === '//') {
      i = skipToEndOfLine(text, i);
      continue;
    }
    if (next2 === '/*') {
      i = skipBlockComment(text, i + 2);
      continue;
    }
    // Text block: `"""…"""`. Must check before regular `"` because the
    // opening triple-quote starts with `"`.
    if (text.slice(i, i + 3) === '"""') {
      const block = consumeTextBlock(text, i);
      out += block.text;
      i = block.index;
      continue;
    }
    const c = text[i];
    if (c === '"') {
      const block = consumeStringLiteral(text, i);
      out += block.text;
      i = block.index;
      continue;
    }
    if (c === "'") {
      const block = consumeCharLiteral(text, i);
      out += block.text;
      i = block.index;
      continue;
    }
    out += c;
    i++;
  }
  return out;
}
 
function skipToEndOfLine(text: string, start: number): number {
  let i = start;
  while (i < text.length && text[i] !== '\n') i++;
  return i;
}
 
function skipBlockComment(text: string, start: number): number {
  // Java block comments do NOT nest. Scan to the first `*/`.
  let i = start;
  while (i < text.length) {
    if (text.slice(i, i + 2) === '*/') return i + 2;
    i++;
  }
  /* v8 ignore next */
  return i;
}
 
function consumeStringLiteral(
  text: string,
  start: number,
): { readonly text: string; readonly index: number } {
  let i = start + 1;
  let buf = '"';
  while (i < text.length) {
    if (text[i] === '\\' && i + 1 < text.length) {
      buf += text.slice(i, i + 2);
      i += 2;
      continue;
    }
    if (text[i] === '"') {
      buf += '"';
      i++;
      break;
    }
    /* v8 ignore next */
    if (text[i] === '\n') break;
    buf += text[i];
    i++;
  }
  return { text: buf, index: i };
}
 
function consumeTextBlock(
  text: string,
  start: number,
): { readonly text: string; readonly index: number } {
  // Text blocks span newlines and end at the next un-escaped `"""`.
  let i = start + 3;
  let buf = '"""';
  while (i < text.length) {
    if (text[i] === '\\' && i + 1 < text.length) {
      buf += text.slice(i, i + 2);
      i += 2;
      continue;
    }
    if (text.slice(i, i + 3) === '"""') {
      buf += '"""';
      i += 3;
      break;
    }
    buf += text[i];
    i++;
  }
  return { text: buf, index: i };
}
 
function consumeCharLiteral(
  text: string,
  start: number,
): { readonly text: string; readonly index: number } {
  let i = start + 1;
  let buf = "'";
  let escape = false;
  while (i < text.length) {
    const c = text[i];
    if (escape) {
      buf += c;
      escape = false;
      i++;
      continue;
    }
    if (c === '\\') {
      buf += c;
      escape = true;
      i++;
      continue;
    }
    if (c === "'") {
      buf += c;
      i++;
      break;
    }
    /* v8 ignore next */
    if (c === '\n') break;
    buf += c;
    i++;
  }
  return { text: buf, index: i };
}
 
function normalizeWhitespace(s: string): string {
  return s.replaceAll(/\s+/g, ' ').trim();
}
 
function sha256(s: string): string {
  return createHash('sha256').update(s, 'utf8').digest('hex');
}
 
// ── output helpers ────────────────────────────────────────────────
 
function record(out: Record<string, FunctionOccurrence[]>, occ: FunctionOccurrence): void {
  const list = out[occ.simpleName];
  if (list) list.push(occ);
  else out[occ.simpleName] = [occ];
}
 
export function isTestFile(rel: string): boolean {
  return TEST_PATH_RE.test(rel) || TEST_FILE_NAME_RE.test(rel);
}
 
function isGeneratedFile(rel: string): boolean {
  return GENERATED_PATH_RE.test(rel);
}