Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
182 changes: 182 additions & 0 deletions usvm-ts-fast-check/fast-check-adapter/src/admitted-statement-lines.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
import { generatedPositionFor, originalPositionFor, TraceMap } from '@jridgewell/trace-mapping';
import type { Profiler } from 'node:inspector';
import { fileURLToPath } from 'node:url';
import ts from 'typescript';

export interface AdmittedStatementLines {
path: string;
hits: Record<number, number>;
partial: boolean;
}

/** V8 range evidence at mapped TypeScript statement starts, aggregated by source line. */
export function admittedStatementLines(
script: Profiler.ScriptCoverage,
generatedSource: string,
sourceMapUrl: string | undefined,
): AdmittedStatementLines | undefined {
const prefix = 'data:application/json;base64,';
if (!sourceMapUrl?.startsWith(prefix)) return undefined;

let map: TraceMap;
try {
map = new TraceMap(Buffer.from(sourceMapUrl.slice(prefix.length), 'base64').toString(), script.url);
} catch {
return undefined;
}
const [sourceUrl] = map.resolvedSources;
const [source] = map.sourcesContent ?? [];
if (sourceUrl === undefined || map.resolvedSources.length !== 1 ||
sourceUrl !== script.url || typeof source !== 'string') return undefined;
const mappedSource = sourceUrl;

const path = fileURLToPath(sourceUrl);
const original = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true);
const generated = ts.createSourceFile('generated.js', generatedSource, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
const functionsByEnd = new Map<number, { fn: Profiler.FunctionCoverage; root: Profiler.CoverageRange }[]>();
for (const fn of script.functions) {
const root = fn.ranges[0];
if (root === undefined) continue;

const group = functionsByEnd.get(root.endOffset) ?? [];
group.push({ fn, root });
functionsByEnd.set(root.endOffset, group);
}

const generatedEnd = generated.statements.at(-1)?.getEnd() ?? 0;
const scriptOwners = script.functions.filter(fn =>
fn.functionName === '' && fn.ranges[0]?.startOffset === 0 && fn.ranges[0].endOffset >= generatedEnd);
const scriptCount = scopeCount(scriptOwners);
const matchedFunctions = new Set(scriptOwners);
const owners: Interval<(offset: number) => number | undefined>[] = [];
let unmatchedObservedFunction = false;

function collectOwners(node: ts.Node): void {
if (ts.isFunctionLike(node) && 'body' in node && node.body !== undefined) {
const start = node.getStart(generated);
const bodyStart = node.body.getStart(generated);
const end = node.getEnd();
const candidates = (functionsByEnd.get(end) ?? [])
.filter(({ root }) => root.startOffset >= start && root.startOffset <= bodyStart)
.map(({ fn }) => fn);
candidates.forEach(fn => matchedFunctions.add(fn));

// Absence is only evidence of zero if all observed function roots can
// be accounted for. A shifted or otherwise unmatched root is ambiguous.
const count = candidates.length === 0
? () => unmatchedObservedFunction ? undefined : 0
: scopeCount(candidates);
owners.push({ start: bodyStart, end, value: count });
} else if (ts.isClassStaticBlockDeclaration(node) || ts.isPropertyDeclaration(node)) {
const body = ts.isClassStaticBlockDeclaration(node) ? node.body : node.initializer;
const isStatic = ts.isClassStaticBlockDeclaration(node) ||
node.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.StaticKeyword);
if (body !== undefined) {
const classStart = node.parent.getStart(generated);
const classEnd = node.parent.getEnd();
const start = body.getStart(generated);
const end = body.getEnd();
const name = isStatic ? '<static_initializer>' : '<instance_members_initializer>';
const candidates = (functionsByEnd.get(classEnd) ?? [])
.filter(({ fn, root }) => fn.functionName === name && root.startOffset >= classStart && root.startOffset <= start)
.map(({ fn }) => fn);
owners.push({ start, end, value: scopeCount(candidates) });
}
}
ts.forEachChild(node, collectOwners);
}
collectOwners(generated);
unmatchedObservedFunction = script.functions.some(fn => !matchedFunctions.has(fn) &&
fn.functionName !== '<static_initializer>' && fn.functionName !== '<instance_members_initializer>');
const ownerAt = innermostAt(owners);

const lines = new Map<number, number | undefined>();
const lineStarts = generated.getLineStarts();
function visit(node: ts.Node): void {
const isRuntimeStatement = ts.isStatement(node) && !ts.isBlock(node) && !ts.isDeclarationStatement(node);
const isConciseArrowBody = node.parent !== undefined && ts.isArrowFunction(node.parent) && node.parent.body === node && !ts.isBlock(node);
const isAnchor = isRuntimeStatement || isConciseArrowBody || ts.isVariableStatement(node) || ts.isClassDeclaration(node);
const anchor = ts.isPropertyDeclaration(node) ? node.initializer : isAnchor ? node : undefined;
if (anchor !== undefined) {
const position = original.getLineAndCharacterOfPosition(anchor.getStart(original));
const line = position.line + 1;
const column = position.character;
const mapped = generatedPositionFor(map, { source: mappedSource, line, column });
let count: number | undefined;
if (mapped.line !== null && mapped.column !== null) {
const back = originalPositionFor(map, { line: mapped.line, column: mapped.column });
if (back.source === sourceUrl && back.line === line && back.column === column) {
const lineStart = lineStarts[mapped.line - 1];
const lineEnd = lineStarts[mapped.line] ?? generatedSource.length;
if (lineStart !== undefined && lineStart + mapped.column < lineEnd) {
const offset = lineStart + mapped.column;
const countInScope = ownerAt(offset) ?? scriptCount;
count = countInScope(offset);
}
}
}

const previous = lines.get(line);
const mixedEvidence = previous !== undefined && count !== undefined && (previous === 0) !== (count === 0);
lines.set(line, count === undefined || lines.has(line) && (previous === undefined || mixedEvidence)
? undefined : Math.max(previous ?? 0, count));
}
ts.forEachChild(node, visit);
}
visit(original);

const hits: AdmittedStatementLines['hits'] = {};
for (const [line, count] of lines) {
if (count !== undefined) hits[line] = count;
}
return { path, hits, partial: Object.keys(hits).length !== lines.size };
}

function scopeCount(candidates: Profiler.FunctionCoverage[]): (offset: number) => number | undefined {
const [fn] = candidates;
if (candidates.length !== 1 || fn === undefined) return () => undefined;
if (fn.ranges[0]?.count === 0) return () => 0;
if (!fn.isBlockCoverage) return () => undefined;

return innermostAt(fn.ranges.map(range => ({ start: range.startOffset, end: range.endOffset, value: range.count })));
}

interface Interval<T> {
start: number;
end: number;
value: T;
}

/** AST scopes and V8 block ranges are each nested or disjoint. */
function innermostAt<T>(intervals: Interval<T>[]): (offset: number) => T | undefined {
const ordered = intervals.sort((left, right) => left.start - right.start || right.end - left.end);
const active: Interval<T>[] = [];
const changes: { offset: number; value: T | undefined }[] = [];
function closeBefore(offset: number): void {
while (active.length !== 0) {
const inner = active[active.length - 1]!;
if (inner.end > offset) break;

active.pop();
changes.push({ offset: inner.end, value: active.at(-1)?.value });
}
}

for (const interval of ordered) {
closeBefore(interval.start);
active.push(interval);
changes.push({ offset: interval.start, value: interval.value });
}
closeBefore(Infinity);

return offset => {
let low = 0;
let high = changes.length;
while (low < high) {
const mid = Math.floor((low + high) / 2);
if (changes[mid]!.offset <= offset) low = mid + 1;
else high = mid;
}
return changes[low - 1]?.value;
};
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
import { Session, type Debugger, type Profiler } from 'node:inspector';
import { parentPort, workerData } from 'node:worker_threads';
import { mergeProcessCovs } from '@bcoe/v8-coverage';
import type { AdmittedStatementLines } from './admitted-statement-lines.js';

export interface ExecutionCoverageSnapshot {
kind: 'coverage';
admittedInvocations: number;
result: Profiler.ScriptCoverage[];
statementLines: AdmittedStatementLines[];
scripts: Record<string, { lineLengths: number[]; sourceMapUrl?: string }>;
}

// The statement pass is supplementary and runs before c8 publishes its report.
// Bound the amount of generated source and inline map it can parse per run.
const MAX_STATEMENT_MAP_CHARACTERS = 256 * 1024;

const port = parentPort;
if (port === null) throw new Error('Coverage collector requires a worker');

Expand Down Expand Up @@ -53,13 +59,27 @@ async function takeSnapshot(command: 'reset' | 'admit' | 'take'): Promise<Execut
}
const result = command === 'take' && workerData.admittedOnly === true ? admitted : coverage.result;
const scripts: ExecutionCoverageSnapshot['scripts'] = Object.create(null);
const statementLines: AdmittedStatementLines[] = [];
let statementCharactersRemaining = MAX_STATEMENT_MAP_CHARACTERS;
for (const script of command === 'take' ? result : []) {
if (!script.url.startsWith('file:')) continue;

const { scriptSource } = await post<Debugger.GetScriptSourceReturnType>(
'Debugger.getScriptSource', { scriptId: scriptIds.get(script.url) ?? script.scriptId },
);
const sourceMapUrl = parsedScripts.get(scriptIds.get(script.url) ?? script.scriptId)?.sourceMapURL;
// Work from the actual generated script in the passive isolate, before c8
// turns the report into a line map and before the separate branch converter.
const isTypeScript = /\.(?:ts|tsx|mts|cts)$/u.test(script.url);
const statementCharacters = scriptSource.length + (sourceMapUrl?.length ?? 0);
const fitsStatementBudget = statementCharacters <= statementCharactersRemaining;
if (workerData.admittedOnly === true && isTypeScript && fitsStatementBudget) {
statementCharactersRemaining -= statementCharacters;
const { admittedStatementLines } = await import('./admitted-statement-lines.js');
const evidence = admittedStatementLines(script, scriptSource, sourceMapUrl);
if (evidence !== undefined) statementLines.push(evidence);
}

scripts[script.url] = {
// V8 offsets are UTF-16 offsets. Keep CR in a CRLF line, like Node's cache.
lineLengths: scriptSource.split(/[\n\u2028\u2029]/).map(line => line.length),
Expand All @@ -72,7 +92,7 @@ async function takeSnapshot(command: 'reset' | 'admit' | 'take'): Promise<Execut
session.disconnect();
}

return { kind: 'coverage', result, scripts, admittedInvocations };
return { kind: 'coverage', result, scripts, admittedInvocations, statementLines };
}

function post<T = unknown>(method: string, params: object = {}): Promise<T> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ export async function startExecutionCoverage(admittedOnly = false, timeoutMillis
mkdirSync(rawDirectory, { recursive: true });
if (admittedOnly) {
writeFileSync(path.join(rawDirectory, 'admitted-count.txt'), String(reportSnapshot.admittedInvocations));
writeFileSync(path.join(rawDirectory, 'admitted-statement-lines.txt'), stringifyProtocolJson(reportSnapshot.statementLines));
}
writeFileSync(path.join(rawDirectory, `coverage-${process.pid}-usvm.json`), stringifyProtocolJson(report));
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ internal object FastCheckDiagnosticCode {

const val COVERAGE_COLLECTOR_NOT_FOUND = "coverage.collector.not-found"
const val COVERAGE_COLLECTION_TIMEOUT = "coverage.collection.timeout"
const val COVERAGE_STATEMENT_PARTIAL = "coverage.statement.partial"
const val COVERAGE_RUNTIME_UNSUPPORTED = "coverage.runtime.unsupported"
const val COVERAGE_RUNTIME_VERSION_UNAVAILABLE = "coverage.runtime.version-unavailable"

Expand Down
Loading
Loading