Files
reverse-engineering-anything/scripts/verify/source-tokens.mjs
T
morluto 332dea76a6 fix(native): keep unreported value-flow and archive coverage unknown, and exempt generation caps by reason marker (#11288)
* fix(native): keep unreported value-flow truncation and archive decode coverage unknown

* test(verify): count multiline optional-fact defaults and pin the guard's exclusions

* fix(domain): keep unknown counts and costs unknown in comparison and coverage summaries (#11325)

* fix(domain): keep unknown counts and costs unknown in comparison and coverage summaries

* refactor(verify): exempt legitimate optional-fact defaults with a reasoned marker (#11355)

* refactor(verify): exempt legitimate optional-fact defaults with a reasoned marker

The optional-fact-default guard counted request defaults and absence that
is modelled elsewhere as hidden unknowns. A comment
`// optional-fact-default: <reason>` on the default's line or the line
before now exempts it; the guard reads unstripped source for the marker and
ignores matches inside comment lines.

Marked: the two evidence paging offsets and four Swift literal reads whose
absence swiftLiteralCoverage reports. Removed instead of marked: jsdiff 9
types Change.count as required, so its two `?? 0` defaults were dead; the
evidence link traversal now carries retained records, so it no longer
re-looks them up behind `?? []`. Baseline 31 -> 22.

* fix(verify): blank comment spans instead of skipping comment-led lines in the optional-fact guard

Skipping a match whose line starts like a comment hid live code after a
leading block comment and counted defaults inside a block comment without
leading stars. The counter now blanks comment text (keeping offsets and line
breaks, skipping string literals) and matches the blanked code, while
exemption markers are still read from the original lines.

* refactor(domain): mark optional-fact defaults whose absence is not an observation (#11389)

* refactor(domain): mark optional-fact defaults whose absence is not an observation

Per-site review of the remaining optional-fact-default entries. Each marked
default is a caller option (trace ignore_fields, environment rules), a list
whose producer omits the empty case (unknown_size_frames, the schema's
min-1 representation_node_ids), caveat text whose completeness another field
carries (call diagnostics, unresolved calls, semantic resource limits), or
absence that already turns the result unknown (Wasm interface inventory,
WebMCP discovery, managed ExportedType rows, legacy integrity mismatch IDs).

Left counted: webCaptureDiff redirects (2; the CDP producer always records
them, so absence is a legacy record that should compare as unknown, not
as no redirects) and HopperCallerReconciliation (2; index-miss semantics not
yet verified). Baseline 22 -> 4.

* fix(browser): compare redirects as unknown when a capture predates redirect recording (#11402)

* fix(browser): compare redirects as unknown when a capture predates redirect recording

The CDP producer records every request's redirect chain, empty when there was none; a record without one predates redirect recording (#986). Comparing it against a current capture reported the network dimension as unchanged, treating the missing chain as "no redirects". Redirects are now compared only when both captures recorded them, and the network dimension is otherwise unknown with a reason; proven membership changes are still reported.

* refactor(hopper): interpret a caller-index miss once at the lookup (#11403)

The forward index holds observations from the examined procedures only, and relationship coverage stays unknown with the scan facts as its reason. A miss therefore adds no callers without showing there are none; the lookup now says so once instead of four optional reads defaulting at each site. The optional-fact-default baseline is now empty.

* docs(javascript): state why an omitted representation list adds no nodes

* fix(verify): count optional-fact defaults from parsed TypeScript, not comment-blanked text

The guard blanked comments with a hand-written scanner and matched a regular expression on the rest, so a default quoted in a string counted and a regular expression holding /* hid the code after it. It now walks the TypeScript syntax tree for property reads defaulted with ?? 0, ?? [] or ?? false, and reads exemption markers only from comment trivia.

* fix(verify): tokenize optional-fact defaults without a compiler and count chained defaults

* fix(verify): match whole optional-fact default expressions across calls and operators

* fix(verify): count optional-fact defaults in template substitutions and after postfix updates, and tie markers to their own expression

* refactor(verify): exempt generation and sample caps from the constant-maximum-slice guard by reason marker (#11454)

* refactor(verify): exempt generation and sample caps from the constant-maximum-slice guard by reason marker

* fix(verify): read reason markers only from real line comments

* fix(verify): read reason markers from the shared source tokenizer

* fix(verify): read a regular expression after a control head as a statement start

The shared tokenizer treated every closing parenthesis as the end of an operand,
so in `if (ready) /[/*]/.test(v)` it read `/[` as division and `/*` inside the
regex as a block comment, hiding the rest of the file from the marker-aware
guards. Parentheses are now tracked: the `)` closing an if/while/for/with head
allows a regular expression, while a call's `)` still means division.

* fix(verify): keep a keyword-named member call out of control-head detection

`policy.if(ready) / (…)` was read as an if-statement head, so the division was
taken for a regular expression and the denominator's optional-fact default was
not counted. A control keyword after `.` or `?.` is a member call.

* refactor(verify): exempt budget-arithmetic cursors and tallies by a not-an-allowance marker (#11493)

* refactor(verify): exempt budget-arithmetic cursors and tallies by a not-an-allowance marker

The budget-arithmetic guard cannot tell a scan cursor, an observed total, a
string being assembled or a tail buffer's retained length from an allowance
when each is compared with a limit. A field declaration marked
`// not-an-allowance: <reason>` (read through the shared reason-marker scan)
is no longer counted. The four remaining sites carry a marker, so the
baseline is empty and removed.

* refactor(verify): exempt detail levels, lifecycle states and domain vocabularies from the completeness-enum guard by reason marker (#11510)

A zod enum containing "complete" is counted as a local coverage vocabulary. Eleven
are not coverage: a caller-chosen detail level, how far a command or session
ran, and format states (GPU decode depth, WASM name section, SQLite column
details). They now carry `// detail-level:`, `// lifecycle-state:` or
`// domain-vocabulary:` with a reason, read through the shared reason-marker
scan (which gains an optional predicate for the matches a guard counts).
local-completeness-enum: 22 -> 11 on this branch.

* fix(verify): bind a not-an-allowance marker to its own class field

Exemptions were a file-wide set of names, so a marked tally in one class hid an
unmarked allowance with the same name in another, and a marked object property
could exempt a class field. Markers now exempt only a member declaration (at
class member depth) of the top-level class that contains it, and the named-
allowance count is taken per class so the same scoping applies to it.

* fix(artifacts): keep main's resources import in the Deno standalone reader after merging main

* fix(verify): start an expression after a template substitution and a non-member keyword, and accept any marker reason

The shared tokenizer read the `/` after `${` as division, so a regular
expression holding `/*` in a substitution hid the rest of the file from
every tokenizer-based guard, and it treated property names such as
`row.return` as keywords. Tokens now record whether template text opens a
substitution and whether a name is an expression keyword (not after `.` or
`?.`), and the regular-expression rule and the optional-fact-default operand
rule read those facts. The optional-fact-default guard reads markers through
reason-marker's isReasonMarker, so any non-empty reason exempts, as for the
other reason markers.

* fix(verify): blank comments with the shared tokenizer before matching architecture guards (#11573)

* fix(verify): blank comments with the shared tokenizer before matching architecture guards

The guards stripped comments with a regular expression that took a `/*`
inside a string, template or regular expression for a comment opener and
deleted code up to the next `*/`. src/flutter/FlutterBuildProvider.ts's
"lib/*/libapp.so" text hid four --pool-policy remediation strings from
cli-option-text-outside-cli. blankComments in source-tokens.mjs now owns
comment removal for the architecture guards and the reason-marker scan: it
blanks comment tokens in place (newlines kept) and keeps strings, templates
and regular expressions. The scan behind it retains only the last tokens it
reads, and whitespace runs are skipped at once.

The cli-option-text-outside-cli baseline records FlutterBuildProvider.ts at
its true count of 4; no other baseline changed.

Fixes #11477

* fix(verify): read a regular expression after a statement block and keep comment offsets for wide characters

The tokenizer now records whether each `{` opens a statement block or an
object literal (from the token before it) and marks the `}` that closes a
block, after which a statement, and so a regular expression, can start; an
object literal's `}` still ends an operand. blankComments replaces each run
of comment text with one space per UTF-16 unit, so a surrogate pair no longer
shifts later offsets.

* chore(verify): drop the Flutter CLI-text baseline entry now that main names no option there
2026-11-16 07:40:30 +08:00

247 lines
8.5 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Splits TypeScript source into code tokens and comments without loading a
// compiler (CI runs the architecture guards before installing dependencies).
// Strings, template text, regular expressions and comments are separate
// tokens, and template substitutions are tracked through nested `${…}` with a
// brace stack, so guards count only executable code and read markers only
// from comments.
const identifier = /[\p{ID_Start}$_#][\p{ID_Continue}$‌‍]*/uy;
const number =
/(?:0[xXbBoO][\da-fA-F_]+|(?:\d[\d_]*(?:\.[\d_]*)?|\.\d[\d_]*)(?:[eE][+-]?\d+)?)n?/uy;
const punctuator =
/\?\?=|\?\?|\?\.(?!\d)|\.\.\.|=>|[!=]==?|[<>]=?|&&=?|\|\|=?|\*\*=?|[-+*%&|^/]=|\+\+|--|[{}()[\];,.<>+\-*/%&|^!~?:=@]/uy;
// After these keywords an expression starts, so `/` opens a regular expression.
// A property name such as `row.return` is not a keyword.
const expressionKeywords = new Set([
"await",
"case",
"delete",
"do",
"else",
"in",
"instanceof",
"new",
"of",
"return",
"throw",
"typeof",
"void",
"yield",
]);
// A parenthesised head after these keywords ends where a statement starts.
const controlKeywords = new Set(["if", "while", "for", "with"]);
// After a closing bracket, `++`, `--`, an operand or a complete template an
// expression has ended, so `/` divides. An expression starts after any other
// punctuator, an expression keyword, the `)` that closes a control head such
// as `if (…)`, and template text that opens a `${` substitution.
const regexAllowedAfter = (token) =>
token === undefined ||
token.opensSubstitution === true ||
token.keyword === true ||
token.closesBlock === true ||
(token.kind === "punct" && token.controlHead === true) ||
(token.kind === "punct" && !/^(?:[)\]}]|\+\+|--)$/u.test(token.text));
// A `{` opens a statement block at the start of a statement, after the `)`
// of a control or function head, an arrow, another brace or `;`, a block
// keyword, or a declaration name or return type (`class A {`,
// `function f(): T {`). Anywhere else it opens an object literal or type,
// whose `}` ends an operand, so a `/` after it divides.
const opensBlock = (previous) =>
previous === undefined ||
(previous.kind === "punct" && /^(?:[);{}]|=>)$/u.test(previous.text)) ||
(previous.kind === "id" &&
(previous.keyword !== true ||
previous.text === "do" ||
previous.text === "else"));
/**
* End of a template's text from `at` (after a backtick or a substitution's
* `}`), and whether that text opens a `${` substitution.
*/
const templateEnd = (source, at, braces) => {
while (at < source.length) {
if (source[at] === "\\") at += 2;
else if (source[at] === "`") return { end: at + 1, opens: false };
else if (source[at] === "$" && source[at + 1] === "{") {
braces.push("template");
return { end: at + 2, opens: true };
} else at += 1;
}
return { end: at, opens: false };
};
/** End of a quoted string opened at `at`. */
const quotedEnd = (source, at) => {
const quote = source[at];
at += 1;
while (at < source.length && source[at] !== quote && source[at] !== "\n")
at += source[at] === "\\" ? 2 : 1;
return at + 1;
};
/** End of a regular expression literal (with flags) opened at `at`. */
const regexEnd = (source, at) => {
at += 1;
let inClass = false;
while (at < source.length && source[at] !== "\n") {
const char = source[at];
if (char === "\\") at += 1;
else if (char === "[") inClass = true;
else if (char === "]") inClass = false;
else if (char === "/" && !inClass) break;
at += 1;
}
identifier.lastIndex = at + 1;
return identifier.test(source) ? identifier.lastIndex : at + 1;
};
/** End of a comment opened at `at`, or undefined when none starts there. */
const commentEnd = (source, at) => {
if (source[at] !== "/") return undefined;
if (source[at + 1] === "/") {
const end = source.indexOf("\n", at);
return end === -1 ? source.length : end;
}
if (source[at + 1] !== "*") return undefined;
const end = source.indexOf("*/", at + 2);
return end === -1 ? source.length : end + 2;
};
/** Whether a name after this token is a property name, not a keyword. */
const isMemberAccess = (token) =>
token?.kind === "punct" && (token.text === "." || token.text === "?.");
const whitespace = /\s+/uy;
const isWhitespace = (char) =>
char === " " || char === "\n" || char === "\t" || /\s/u.test(char);
const wordPatterns = [
["id", identifier],
["number", number],
["punct", punctuator],
];
/** An identifier, number or punctuator token at `at`. */
const wordToken = (source, at) => {
for (const [tokenKind, pattern] of wordPatterns) {
pattern.lastIndex = at;
if (pattern.test(source))
return {
kind: tokenKind,
text: source.slice(at, pattern.lastIndex),
start: at,
};
}
return undefined;
};
/**
* Scans source into code tokens and comments. The scanner reads only the last
* two tokens, so a caller that needs only comments keeps no more than those.
*/
const scan = (source, keepTokens) => {
/** @type {import("./source-tokens.d.mts").SourceToken[]} */
const tokens = [];
// One entry per open `(`: whether it opens a control head.
const parens = [];
/** @type {{ text: string, end: number }[]} */
const comments = [];
const braces = [];
let at = 0;
while (at < source.length) {
const char = source[at];
const start = at;
const comment = commentEnd(source, at);
if (isWhitespace(char)) {
whitespace.lastIndex = at;
whitespace.test(source);
at = whitespace.lastIndex;
} else if (comment !== undefined) {
at = comment;
comments.push({ text: source.slice(start, at), end: at });
} else if (char === "'" || char === '"') {
at = quotedEnd(source, at);
tokens.push({ kind: "string", text: "", start });
} else if (char === "`" || (char === "}" && braces.at(-1) === "template")) {
if (char === "}") braces.pop();
const text = templateEnd(source, at + 1, braces);
at = text.end;
// Template text after a substitution's `}` closes that substitution.
tokens.push({
kind: char === "}" ? "substitution-end" : "string",
text: "",
start,
...(text.opens ? { opensSubstitution: true } : {}),
});
} else if (char === "/" && regexAllowedAfter(tokens.at(-1))) {
at = regexEnd(source, at);
tokens.push({ kind: "regex", text: "", start });
} else {
const token = wordToken(source, at);
if (token === undefined) {
at += 1;
continue;
}
at = start + token.text.length;
if (token.text === "(") {
const previous = tokens.at(-1);
// `x.if(…)` and `x?.for(…)` are member calls, not control heads.
parens.push(
previous?.kind === "id" &&
controlKeywords.has(previous.text) &&
!isMemberAccess(tokens.at(-2)),
);
} else if (token.text === ")" && parens.pop() === true)
token.controlHead = true;
else if (
token.kind === "id" &&
expressionKeywords.has(token.text) &&
!isMemberAccess(tokens.at(-1))
)
token.keyword = true;
if (token.text === "{")
braces.push(opensBlock(tokens.at(-1)) ? "block" : "object");
// After a statement block a new statement starts.
else if (token.text === "}" && braces.pop() === "block")
token.closesBlock = true;
tokens.push(token);
if (!keepTokens && tokens.length > 64) tokens.splice(0, 62);
}
}
return { tokens, comments };
};
/**
* Splits TypeScript source into code tokens and comments. Template literals
* are tracked through nested `${…}` substitutions with a brace stack.
*/
export const tokenize = (source) => scan(source, true);
/**
* The source with every comment replaced by spaces, keeping newlines, so
* offsets and line numbers still match the source. Strings, templates and
* regular expressions are kept, so `/*` or `//` inside them is not a comment.
* @param {string} source
* @param {readonly { text: string, end: number }[]} [comments] the source's
* comments, when the caller has already tokenized it
*/
export const blankComments = (
source,
comments = scan(source, false).comments,
) => {
const parts = [];
let last = 0;
for (const { text, end } of comments) {
parts.push(source.slice(last, end - text.length));
// One space per UTF-16 unit, so offsets after the comment stay the same.
parts.push(text.replace(/[^\n]+/gu, (run) => " ".repeat(run.length)));
last = end;
}
parts.push(source.slice(last));
return parts.join("");
};