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 | 1x 1x 1x 1x 1x 32x 32x 32x 32x 32x 32x 45x 45x 45x 45x 45x 45x 32x 32x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 58x 3x 58x 6x 6x 58x 45x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 6x 6x 6x 6x 6x 6x 6x 6x 6x 4x 4x 4x 2x 2x 2x 6x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 4x 4x 2x 2x 2x 2x 2x 2x 3x 3x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 495x 495x 4x 4x 4x 495x 47x 47x 47x 495x 4x 4x 495x 24x 24x 24x 24x 24x 24x 24x 495x 440x 4x 4x 4x 4x 4x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 42x 5x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 32x 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 4x 4x 4x 4x 4x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 51x 51x 51x 51x 47x 47x 47x 51x 51x 51x 51x 51x 51x 51x 51x 23x 23x 23x 51x 51x 23x 23x 23x 18x 18x 23x 23x 23x 3x 3x 3x 3x 3x 3x 3x 3x 23x 23x 47x 47x 51x 51x 51x 51x 45x 45x 45x 45x 51x 51x 51x 96x 96x 96x 96x 3986x 3986x 3x 3x 3x 3986x 8x 8x 8x 8x 8x 3975x 3975x 3975x 96x 96x 51x 51x 51x 51x 51x 96x 96x 96x 96x 96x 96x 96x 96x 96x 95x 96x 1x 50x 50x 45x 45x 45x | /**
* Python walkProject — emit FunctionOccurrences + CallSiteRecords.
*
* One descent per file, mirroring lang-typescript/walk.ts. Identifies
* five callable shapes:
*
* - `function_definition` outside a class body → 'function-declaration'
* - `function_definition` inside a class body → 'method'
* - `function_definition` named `__init__` → 'constructor'
* - `lambda` → 'arrow'
* - one synthetic `<module-init>` per file
*
* Body hashing: sha256 of normalized body text. "Normalized" means:
* 1. Strip Python comments (`#` to end-of-line).
* 2. Strip module-level / function-level docstrings — recognized as
* a leading `expression_statement` whose only child is a `string`.
* This is the textually-conservative choice; pretty-formatter
* normalization (e.g. ruff/black-style reflow) is out of scope.
* 3. Collapse all whitespace runs to a single space, trim.
*
* Only string literals **at the top of a function body** are stripped
* as docstrings. String literals embedded in expressions are preserved.
*
* Call-site records:
* - `call` node — every Python call expression (`foo()`, `obj.method(...)`,
* `f.g.h()`).
* - 'creation' edges — for each `lambda` expression nested inside a
* parent function/method/module-init, emit a creation edge so
* reachability flows through closures even when the lambda's
* dispatch is unresolvable. Mirror of lang-typescript's
* `isInlineCallable` rule applied to lambdas.
*
* Test detection happens here too (mirrors lang-typescript): we don't
* emit special records, but we tag each occurrence's `inTestFile` flag
* via the path predicate.
*/
import { createHash } from 'node:crypto';
import { relative, sep } from 'node:path';
import type { PythonParsedFile, PythonParsedProject } 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 = /(?:^|\/)tests?\//;
const TEST_FILE_NAME_RE = /(?:^|\/)test_[^/]+\.py$|_test\.py$/;
const GENERATED_PATH_RE = /\bdist\/|\bbuild\/|\.generated\./;
export function walkProject(input: WalkInput<PythonParsedProject>): WalkOutput {
const occurrences: Record<string, FunctionOccurrence[]> = Object.create(null) as Record<
string,
FunctionOccurrence[]
>;
const callSites: CallSiteRecord[] = [];
const dependencySites: DependencySiteRecord[] = [];
const parseErrors: ParseError[] = [];
// Iterate files in stable order so I-1 (determinism) holds.
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: PythonParsedFile,
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 moduleInit = synthesizeModuleInit(file, filePathProjectRel, inTestFile, definedInGenerated);
record(out, moduleInit);
// Phase 4 (DEC-498): walk top-level imports as dependency sites. Owner
// is the file's synthesized module-init occurrence.
collectDependencySites(file, moduleInit.bodyHash, dependencySites);
const initialFrame: Frame = {
ownerHash: moduleInit.bodyHash,
enclosingClass: null,
};
const ctx: WalkCtx = {
file,
filePathProjectRel,
inTestFile,
definedInGenerated,
out,
callSites,
};
for (const child of file.tree.rootNode.children) visit(child, initialFrame, ctx);
}
/**
* Walk a Python file's top-level statements for `import_statement` and
* `import_from_statement` nodes; emit one `DependencySiteRecord` per
* imported module (not per imported name). The owner is the file's
* synthesized module-init occurrence (every file has exactly one).
*
* Phase 4 of opensip's substrate consolidation (DEC-498). The emitted
* `specifier` preserves the raw dotted module path as written, including
* any leading dots for relative imports (`'.foo'`, `'..pkg.bar'`).
*
* Out of scope at v1:
* - Wildcard `from foo import *` is treated like any other from-import:
* one dep site on the source module (`foo`); the `*` semantics
* (re-exports) are not modelled.
* - `__all__` semantics, dynamic `__import__` / `importlib.import_module`,
* and conditional / nested imports inside function bodies (only
* top-level imports are emitted).
*/
function collectDependencySites(
file: PythonParsedFile,
moduleInitHash: string,
out: DependencySiteRecord[],
): void {
for (const stmt of file.tree.rootNode.namedChildren) {
if (stmt.type === 'import_statement') {
collectFromImportStatement(stmt, file, moduleInitHash, out);
} else if (stmt.type === 'import_from_statement') {
collectFromImportFromStatement(stmt, file, moduleInitHash, out);
}
}
}
/**
* `import foo`, `import foo.bar`, `import foo as f`, `import a, b.c, d`.
* Each name child is either a `dotted_name` or an `aliased_import` whose
* `name` field is a `dotted_name`. Emits one dep site per top-level
* comma-separated target.
*/
function collectFromImportStatement(
stmt: Parser.SyntaxNode,
file: PythonParsedFile,
moduleInitHash: string,
out: DependencySiteRecord[],
): void {
for (const child of stmt.namedChildren) {
const dotted = resolveImportedNameDotted(child);
if (!dotted) continue;
pushDependencySite(stmt, file, moduleInitHash, dotted.text, out);
}
}
/**
* `from foo import x`, `from foo.bar import a, b`, `from . import x`,
* `from .pkg import y`, `from ..parent import z`.
*
* The module-name field encodes the source module:
* - `dotted_name` → absolute import (`from foo.bar import …`)
* - `relative_import` → leading dot(s) + optional `dotted_name`
*
* For `from . import name`, the relative_import has only dots (no
* trailing dotted_name); the specifier is the leading-dot string
* (e.g. `'.'`) — the *imported names* are themselves modules to resolve.
* To preserve the one-dep-site-per-imported-module rule for this shape,
* we walk the `name` field too and emit one site per imported name,
* each carrying the prefix-dots + name (e.g. `.sibling`).
*
* For all other relative shapes (`from .pkg import x`, `from ..pkg.sub
* import y`), the relative_import already carries the module path; we
* emit ONE dep site with the raw relative-import text as specifier.
*/
function collectFromImportFromStatement(
stmt: Parser.SyntaxNode,
file: PythonParsedFile,
moduleInitHash: string,
out: DependencySiteRecord[],
): void {
const moduleNameField = stmt.childForFieldName('module_name');
if (!moduleNameField) return;
if (moduleNameField.type === 'dotted_name') {
pushDependencySite(stmt, file, moduleInitHash, moduleNameField.text, out);
return;
}
if (moduleNameField.type === 'relative_import') {
collectFromRelativeImport(stmt, moduleNameField, file, moduleInitHash, out);
}
}
/**
* Handle the `from <relative_import> import …` case. Splits into two
* shapes:
* - relative_import carries an inner dotted_name (`from .pkg import x`)
* → ONE dep site with `prefix + inner` as specifier.
* - relative_import is dots-only (`from . import sibling, other`)
* → ONE dep site PER imported name, specifier `prefix + name`.
*/
function collectFromRelativeImport(
stmt: Parser.SyntaxNode,
moduleNameField: Parser.SyntaxNode,
file: PythonParsedFile,
moduleInitHash: string,
out: DependencySiteRecord[],
): void {
const prefix = relativeImportPrefix(moduleNameField);
const innerDotted = relativeImportInnerDotted(moduleNameField);
if (innerDotted !== null) {
// `from .pkg import x` — one site, specifier = '.pkg'
pushDependencySite(stmt, file, moduleInitHash, prefix + innerDotted, out);
return;
}
// `from . import sibling, other` — one site PER imported name,
// specifier = `.sibling`, `.other`.
for (const named of stmt.namedChildren) {
if (named === moduleNameField) continue;
const dotted = resolveImportedNameDotted(named);
if (!dotted) continue;
pushDependencySite(stmt, file, moduleInitHash, prefix + dotted.text, out);
}
}
/**
* Resolve an imported-name child to its `dotted_name` node, if any.
* Accepts either a bare `dotted_name` or an `aliased_import` whose
* `name` field is a `dotted_name`. Returns null for anything else
* (e.g. punctuation, comments).
*/
function resolveImportedNameDotted(named: Parser.SyntaxNode): Parser.SyntaxNode | null {
if (named.type === 'dotted_name') return named;
if (named.type === 'aliased_import') {
const nameField = named.childForFieldName('name');
if (nameField?.type === 'dotted_name') return nameField;
}
return null;
}
function relativeImportPrefix(node: Parser.SyntaxNode): string {
// The `import_prefix` child carries the leading dots as raw text.
for (const child of node.children) {
if (child.type === 'import_prefix') return child.text;
}
/* v8 ignore next */
return '';
}
function relativeImportInnerDotted(node: Parser.SyntaxNode): string | null {
for (const child of node.namedChildren) {
if (child.type === 'dotted_name') return child.text;
}
return null;
}
function pushDependencySite(
stmt: Parser.SyntaxNode,
file: PythonParsedFile,
ownerHash: string,
specifier: string,
out: DependencySiteRecord[],
): void {
out.push({
nodeRef: stmt,
sourceFileRef: file,
ownerHash,
specifier,
line: stmt.startPosition.row + 1,
column: stmt.startPosition.column,
});
}
interface Frame {
readonly ownerHash: string;
readonly enclosingClass: string | null;
}
interface WalkCtx {
readonly file: PythonParsedFile;
readonly filePathProjectRel: string;
readonly inTestFile: boolean;
readonly definedInGenerated: boolean;
readonly out: Record<string, FunctionOccurrence[]>;
readonly callSites: CallSiteRecord[];
}
function visit(node: Parser.SyntaxNode, frame: Frame, ctx: WalkCtx): void {
if (node.type === 'class_definition') {
visitClass(node, frame, ctx);
return;
}
if (node.type === 'function_definition') {
visitFunction(node, frame, ctx);
return;
}
if (node.type === 'lambda' && visitLambdaNode(node, frame, ctx)) {
return;
}
if (node.type === 'call') {
ctx.callSites.push({
nodeRef: node,
sourceFileRef: ctx.file,
ownerHash: frame.ownerHash,
kind: 'call',
});
}
for (const child of node.children) visit(child, frame, ctx);
}
function visitClass(node: Parser.SyntaxNode, frame: Frame, ctx: WalkCtx): void {
const className = nameOf(node) ?? '<anon-class>';
// Don't emit a function for the class itself — Python classes are
// declarations whose top-level statements run at module load. Keep
// the module-init as the owner; descend with class context for
// nested function_definitions to be tagged as methods.
const childFrame: Frame = { ownerHash: frame.ownerHash, enclosingClass: className };
for (const child of node.children) visit(child, childFrame, ctx);
}
function visitFunction(node: Parser.SyntaxNode, frame: Frame, ctx: WalkCtx): void {
const occ = visitFunctionDefinition(
node,
ctx.file,
ctx.filePathProjectRel,
frame.enclosingClass,
ctx.inTestFile,
ctx.definedInGenerated,
);
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 visitLambdaNode(node: Parser.SyntaxNode, frame: Frame, ctx: WalkCtx): boolean {
const occ = visitLambda(node, ctx.file, ctx.filePathProjectRel, ctx.inTestFile, ctx.definedInGenerated);
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 visitFunctionDefinition(
node: Parser.SyntaxNode,
file: PythonParsedFile,
filePathProjectRel: string,
enclosingClass: string | null,
inTestFile: boolean,
definedInGenerated: boolean,
): FunctionOccurrence | null {
const name = nameOf(node) ?? '<anon-fn>';
const digest = digestPythonBody(file.source.slice(node.startIndex, node.endIndex));
const kind = classifyFunctionKind(name, enclosingClass);
const qualifiedBase = filePathProjectRel.replace(/\.py$/, '').split('/').join('.');
const qualifiedName = enclosingClass === null
? `${qualifiedBase}.${name}`
: `${qualifiedBase}.${enclosingClass}.${name}`;
return {
bodyHash: digest.hash,
bodySize: digest.size,
simpleName: name,
qualifiedName,
filePath: filePathProjectRel,
line: node.startPosition.row + 1,
column: node.startPosition.column,
endLine: node.endPosition.row + 1,
kind,
params: extractParams(node),
returnType: null,
enclosingClass,
decorators: extractDecorators(node),
visibility: name.startsWith('_') ? 'module-local' : 'exported',
inTestFile,
definedInGenerated,
calls: [],
};
}
function classifyFunctionKind(
name: string,
enclosingClass: string | null,
): FunctionOccurrence['kind'] {
if (enclosingClass === null) return 'function-declaration';
if (name === '__init__') return 'constructor';
return 'method';
}
function visitLambda(
node: Parser.SyntaxNode,
file: PythonParsedFile,
filePathProjectRel: string,
inTestFile: boolean,
definedInGenerated: boolean,
): FunctionOccurrence | null {
const digest = digestPythonBody(file.source.slice(node.startIndex, node.endIndex));
const startLine = node.startPosition.row + 1;
const startCol = node.startPosition.column;
const simpleName = `<arrow:${filePathProjectRel}:${String(startLine)}:${String(startCol)}>`;
const qualifiedBase = filePathProjectRel.replace(/\.py$/, '').split('/').join('.');
return {
bodyHash: digest.hash,
bodySize: digest.size,
simpleName,
qualifiedName: `${qualifiedBase}.<lambda:${String(startLine)}:${String(startCol)}>`,
filePath: filePathProjectRel,
line: startLine,
column: startCol,
endLine: node.endPosition.row + 1,
kind: 'arrow',
params: extractParamsFromField(node, 'parameters'),
returnType: null,
enclosingClass: null,
decorators: [],
visibility: 'private',
inTestFile,
definedInGenerated,
calls: [],
};
}
function synthesizeModuleInit(
file: PythonParsedFile,
filePathProjectRel: string,
inTestFile: boolean,
definedInGenerated: boolean,
): FunctionOccurrence {
// Hash the file's top-level statement-text concatenation. Mirrors
// lang-typescript's synthesizeModuleInit shape.
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 = filePathProjectRel.replace(/\.py$/, '').split('/').join('.');
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 extractParams(node: Parser.SyntaxNode): readonly { name: string; optional: boolean; rest: boolean }[] {
return extractParamsFromField(node, 'parameters');
}
function extractParamsFromField(
node: Parser.SyntaxNode,
fieldName: string,
): readonly { name: string; optional: boolean; rest: boolean }[] {
const params = node.childForFieldName(fieldName);
if (!params) return [];
const out: { name: string; optional: boolean; rest: boolean }[] = [];
for (const child of params.namedChildren) {
const param = extractParam(child);
if (param) out.push(param);
}
return out;
}
function extractParam(child: Parser.SyntaxNode): { name: string; optional: boolean; rest: boolean } | null {
switch (child.type) {
case 'identifier': {
return { name: child.text, optional: false, rest: false };
}
case 'typed_parameter':
case 'default_parameter':
case 'typed_default_parameter': {
const name = child.childForFieldName('name') ?? child.namedChild(0);
if (!name) return null;
return {
name: name.text,
optional: child.type === 'default_parameter' || child.type === 'typed_default_parameter',
rest: false,
};
}
/* v8 ignore start */
case 'list_splat_pattern':
case 'dictionary_splat_pattern': {
const name = child.namedChild(0);
if (!name) return null;
return { name: name.text, optional: false, rest: true };
}
default: {
return null;
}
/* v8 ignore stop */
}
}
function extractDecorators(node: Parser.SyntaxNode): readonly string[] {
// tree-sitter-python wraps a function_definition in a `decorated_definition`
// node when decorators are present. The decorators are siblings of the
// function_definition inside that wrapper.
if (node.parent?.type !== 'decorated_definition') return [];
/* v8 ignore start */
const out: string[] = [];
for (const child of node.parent.namedChildren) {
if (child.type === 'decorator') {
// Decorator text is `@expr`; trim the leading `@`.
const text = child.text.trim();
out.push(text.startsWith('@') ? text.slice(1) : text);
}
}
return out;
/* v8 ignore stop */
}
// ── body normalization ────────────────────────────────────────────
interface BodyDigest {
readonly hash: string;
readonly size: number;
}
function digestPythonBody(text: string): BodyDigest {
const normalized = normalizePythonBody(text);
return { hash: sha256(normalized), size: normalized.length };
}
function digestSyntheticBody(text: string): BodyDigest {
const normalized = normalizeWhitespace(stripPythonComments(text));
return { hash: sha256(normalized), size: normalized.length };
}
/**
* Strip Python `#` comments and leading-of-body docstrings, then
* collapse whitespace. Docstring detection is line-oriented and
* conservative: a line containing only a triple-quoted string at the
* top of the body is removed. This is good enough for the v1 contract;
* a parse-tree-driven version is a follow-up if FP rates demand it.
*/
function normalizePythonBody(text: string): string {
return normalizeWhitespace(stripPythonComments(stripLeadingDocstring(text)));
}
function stripPythonComments(text: string): string {
// Walk character-by-character, respecting string literals (so `#`
// inside a string is preserved). Python strings are wrapped by `'`,
// `"`, or triple-quoted variants.
let out = '';
let i = 0;
while (i < text.length) {
const c = text[i];
if (c === '#') {
i = skipToEndOfLine(text, i);
continue;
}
if (c === '"' || c === "'") {
const next = consumeStringLiteral(text, i, c);
out += next.text;
i = next.index;
continue;
}
out += c;
i++;
}
return out;
}
/* v8 ignore start */
function skipToEndOfLine(text: string, start: number): number {
let i = start;
while (i < text.length && text[i] !== '\n') i++;
return i;
}
function consumeStringLiteral(
text: string,
start: number,
quote: string,
): { readonly text: string; readonly index: number } {
const triple = text.slice(start, start + 3) === `${quote}${quote}${quote}`;
const close = triple ? `${quote}${quote}${quote}` : quote;
let i = start + (triple ? 3 : 1);
let buf = text.slice(start, i);
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 + close.length) === close) {
buf += close;
i += close.length;
break;
}
buf += text[i];
i++;
}
return { text: buf, index: i };
}
/* v8 ignore stop */
function stripLeadingDocstring(text: string): string {
// Match an optional whitespace prefix followed by a triple-quoted
// string, optionally followed by a newline. Conservative — only
// handles the common case at the start of the function/module body.
const match = /^\s*(?:[ru]?(?:'''[\s\S]*?'''|"""[\s\S]*?"""))\s*\n/i.exec(text);
if (match) return text.slice(match[0].length);
return text;
}
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);
}
|