Skip to content

perf(str): add a size hint to JSStr UTF-16 encoding - #26744

Closed
Dunqing wants to merge 31 commits into
mainfrom
jsstr-encode-utf16-size-hint
Closed

Dunqing wants to merge 31 commits into
mainfrom
jsstr-encode-utf16-size-hint

Conversation

@Dunqing

@Dunqing Dunqing commented Sep 17, 2026 •

Copy link
Copy Markdown
Member

EncodeUtf16 reported the default size hint of zero, so collecting code units into a vector grew it incrementally through doubling. The NAPI boundary collects UTF-16 units from string values, paying that growth on every conversion.

Report a lower bound of one unit per three bytes, the fewest any WTF-8 byte sequence can yield, and an upper bound of one unit per byte, each adjusted for a buffered trail unit mid-pair. Collecting now reserves once:

encode_utf16().collect::<Vec<u16>>() before after
32-byte string 100.8 ns 77.0 ns
1KB string 1574.2 ns 850.1 ns

Verified with a test asserting the bounds bracket the remaining units at every iteration step across ASCII, multi-byte, lone-surrogate, and paired inputs.

Ninth PR in the JSStr stack, based on the escape-table cleanup. Part of #26242.

Implemented with AI assistance.

Dunqing commented Sep 17, 2026 •

Copy link
Copy Markdown
Member Author

Warning

This pull request is not mergeable via GitHub because a downstack PR is open. Once all requirements are satisfied, merge this PR as a stack on Graphite.
Learn more


How to use the Graphite Merge Queue

Add either label to this PR to merge it via the merge queue:

  • 0-merge - adds this PR to the back of the merge queue
  • hotfix - for urgent changes, fast-track this PR to the front of the merge queue

You must have a Graphite account in order to use the merge queue. Sign up using this link.

An organization admin has enabled the Graphite Merge Queue in this repository.

Please do not merge from GitHub as this will restart CI on PRs being processed by the merge queue.

This stack of pull requests is managed by Graphite. Learn more about stacking.

@codspeed

codspeed Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 87 untouched benchmarks
⏩ 9 skipped benchmarks1


Comparing jsstr-encode-utf16-size-hint (134721d) with jsstr-estree-escape-table (4638a94)2

Open in CodSpeed

Footnotes

  1. 9 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

  2. No successful run was found on jsstr-estree-escape-table (2827923) during the generation of this report, so fcf204b was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

JavaScript strings can contain lone surrogates that Rust str cannot
represent. Introduce arena-backed primitives with explicit encoding
invariants before migrating AST consumers.

Part of #26242.
Defer metadata packing and benchmarks until a concrete performance need
arises. Keep the initial API review focused on correctness and safety.
Follow the existing string builder and Rust naming conventions so the
new API is familiar before callers adopt it.

Implemented with AI assistance.
Keep the initial public API limited to operations needed by consumers.
Test fixtures can build values through a private helper; unused
convenience conversions can be added when callers need them.

Implemented with AI assistance.
Rechecking properties already established by the UTF-8 fast path
obscures the slow path's precondition.

Implemented with AI assistance.
@Dunqing
Dunqing force-pushed the jsstr-encode-utf16-size-hint branch from 5615ee7 to e9e1efe Compare September 21, 2026 01:14
@Dunqing
Dunqing force-pushed the jsstr-estree-escape-table branch from 9d96a3d to d95bac0 Compare September 21, 2026 01:14
@github-actions github-actions Bot added the A-linter Area - Linter (oxlint): rules, config, diagnostics, fixes. Add L-* labels for details label Sep 21, 2026
@Dunqing
Dunqing force-pushed the jsstr-estree-escape-table branch from 10d5ca4 to 5cfc1f0 Compare September 21, 2026 01:48
@Dunqing
Dunqing force-pushed the jsstr-encode-utf16-size-hint branch 2 times, most recently from 0689ee9 to ab69599 Compare September 21, 2026 01:54
@Dunqing
Dunqing force-pushed the jsstr-estree-escape-table branch from 5cfc1f0 to 23971d1 Compare September 21, 2026 01:54
@Dunqing
Dunqing force-pushed the jsstr-encode-utf16-size-hint branch from ab69599 to 6d6357e Compare September 21, 2026 02:54
Use the core array constructor for repeated template concatenations.
Keep diagnostic formatting borrowed for UTF-8 values and make the
remaining fallback policies explicit. The JSX curly-brace fixer must
decline a value it cannot decode instead of printing its source spelling
as a new JavaScript string.

Consolidate AST debug formatting without changing its output and use
consistent JSStr imports at the remaining conversion sites. Keep shared
printer iteration and surrogate concat folding as separate follow-ups.

Part of #26242.

Implemented with AI assistance.
Add a conformance fixture for enum members with surrogate string
values: literal and concatenated values emit their runtime-equivalent
form, and an uncached member reference pins the conceded extra reverse
mapping. The updated TypeScript suite gains
braceEscapedSurrogatePairLiteralType, which now passes for codegen,
ESTree, and the transformer. Comment the JSX attribute value gates in
five rules: a plain attribute value is raw source text and never
contains a lone surrogate, so those paths are unreachable in lint.

Implemented with AI assistance.
The specification requires module export names to be well-formed
Unicode, and the parser reports the syntax error for a string form
containing a lone surrogate, but ModuleExportName::name still returned
JSStr. Every consumer carried a decline branch for a case that cannot
occur in a valid module.

Return Str, with the guarantee documented on the method. In the
recovered AST of a program with that syntax error the name reads back
as the replacement character, and the module-record builder omits
entries for such names explicitly instead of recording the replacement.
The consumer gates in the record builder, the linter, and the
transformers are removed. Module sources and import attributes are
unchanged: any string value is legal there, so they stay JSStr.

Implemented with AI assistance.
The module-record builder returned before registering export names when
a re-export's module request held a lone surrogate, so the
duplicate-export check never saw those names:
`export { a } from "\uD800"; export const a = 1;` and the
`export * as a from` form were accepted, although both are early errors
that the base and Node reject.

Register the exported names before examining the module request. Only
the request metadata still waits on the module-record migration.

Implemented with AI assistance.
@Dunqing
Dunqing force-pushed the jsstr-estree-escape-table branch from ba61d2c to 4638a94 Compare September 21, 2026 07:04
@Dunqing
Dunqing force-pushed the jsstr-encode-utf16-size-hint branch from 6d6357e to c9b45df Compare September 21, 2026 07:04
When a member's value could not be evaluated, the lowering decided its
reverse mapping from the initializer's syntax alone, and a reference to
another member never looks like a string. With lone surrogates this
happens to ordinary constants: in
`enum E { "𐀀" = 1, A = "\uD800" + "\uDC00", B = A }` the evaluator
skips A, B = A gets a reverse mapping, and `E[E.A] = "B"` overwrites
the member named "𐀀". TypeScript keeps that member at 1.

Follow TypeScript's rule instead: a member is a string when its
initializer is a string literal, a template literal, a `+` with a string
side, or a reference to a string member of the same or an earlier enum,
even if that member's value could not be evaluated. This also matches
TypeScript for non-constant string members such as `B = A` after
`A = f() + "x"`, which previously got a reverse mapping as well.

Implemented with AI assistance.
A decoded property name can be static without being valid Rust UTF-8.
Return JSStr from member-name helpers so comparisons retain the actual
UTF-16 value and consumers no longer mistake these names for dynamic
expressions.

Keep explicit UTF-8 conversions at fixed-name lookups and existing
UTF-8-only APIs. Cover AST helpers, self-assignment and console diagnostics,
React display names, and declaration enum references with regressions.
Object/class key APIs and module-record storage remain separate work.

Part of #26242.

Implemented with AI assistance.
The generated ESTree implementations in this crate serialize `Span`, but
the `serialize` feature did not enable `oxc_span/serialize`. Building the
crate alone with all features therefore failed to compile; workspace
builds only succeeded because other crates unified that feature in.

Part of #26242.

Implemented with AI assistance.
A numeric character reference in JSX text or an attribute value can name
a lone surrogate, such as `&#xD800;`, and two references such as
`&#xD83D;&#xDE00;` form one surrogate pair. Babel decodes both. The shared
entity decoder used `char::from_u32`, so it left these references as
literal `&#...;` text, and the JSX transform emitted that text as the
string value.

Decode entities into a `JSStrBuilder`. A reference to a lone surrogate
becomes that code unit, adjacent lead and trail references combine into
one supplementary character, and named or non-surrogate references decode
as before. Text without entities is still borrowed without copying.
`decode_entity` exposes the per-reference decoding so other consumers can
share it. Only lowercase `x` selects hexadecimal, matching Babel.

Cover attributes and text children in both runtimes, with a runtime check
of the exact UTF-16 units, and the attribute cold path in codegen that
prints a lone-surrogate value as a string expression.

Part of #26242.

Implemented with AI assistance.
The compiler had its own JSX entity decoder that produced Rust strings, so
a numeric reference to a lone surrogate stayed as literal `&#...;` text and
two references forming a pair were never combined. Babel decodes both.

Use the shared decoder from `oxc_syntax`, which produces a `JSStr`. JSX
text is trimmed on JavaScript code points so a decoded lone surrogate
survives whitespace cleanup, and the source-offset walk for the trimmed
text accounts for a pair formed from two references. Decoded text that
cannot be written as JSX text is emitted as a string expression child,
matching how the compiler already prints attribute values with lone
surrogates.

The shared decoder accepts only lowercase `x` for hexadecimal references,
so `&#X41;` now stays literal, as it does in Babel.

Part of #26242.

Implemented with AI assistance.
Consumers that only need to know whether a JavaScript string contains
some text had to convert it to UTF-8 first, so an unrelated lone
surrogate elsewhere in the value suppressed the match. This lost lint
diagnostics for values such as " \uD800 ".

Add contains, starts_with, ends_with, find, and rfind on JSStr with the
str argument forms that consumers use: &str, char, and char predicates,
through a sealed JSStrPattern trait. Text patterns are searched byte for
byte in canonical WTF-8, which finds exactly the UTF-16 matches because
a UTF-8 pattern cannot start or end inside another code point's
encoding and never equals a lone surrogate's encoding. Predicates decode
code points and never match a lone surrogate, since no char exists for
it; the trait documents that a negated predicate therefore does not see
every code point. Offsets are WTF-8 byte offsets, like the UTF-8 byte
offsets of str::find.

Tests compare every method and pattern form with str on UTF-8 input and
with a UTF-16 reference model around lone lead and trail surrogates,
pairs formed across a boundary, and empty patterns.

Part of #26242.

Implemented with AI assistance.
Several rules converted a string value to UTF-8 before looking for a
character or prefix, so a lone surrogate anywhere in the value hid text
elsewhere in it. jest/valid-title missed the surrounding spaces in
" \uD800 " and the duplicate prefix in "test \uD800", and
no-template-curly-in-string, no-script-url, no-regex-spaces,
no-webpack-loader-syntax, node/no-sync, and jest/prefer-lowercase-title
missed the text they check next to a surrogate.

Use the JSStr search methods for these checks so the complete value is
inspected. Where a rule still needs UTF-8, the conversion is confined to
that step: valid-title skips only its regular-expression checks for a
surrogate title, prefer-lowercase-title reports without its UTF-8 fix,
and no-sync and no-webpack-loader-syntax render the name with escapes
or its source spelling in the message. A title that begins with a lone
surrogate has no case, so prefer-lowercase-title accepts it.

Cover each rule with a surrogate beside the matched text and with a
surrogate as the only content.

Part of #26242.

Implemented with AI assistance.
…sion

The multiline checks for JSX string attributes converted the value to
UTF-8 before looking for a newline, so a lone surrogate elsewhere in the
value would have hidden the newline. The parser does not decode
surrogates into JSX attribute values today, so output is unchanged; use
the JSStr search method so the check holds once it does.

Part of #26242.

Implemented with AI assistance.
The lowercase-title help text renders the title with Debug formatting.
Pin the rendering of apostrophes and double quotes so it stays identical
to str output for ordinary titles.

Part of #26242.

Implemented with AI assistance.
…one surrogates

Many rules converted a string value with `as_str()` and returned when that
failed, so any lone surrogate anywhere in the string disabled the check,
including prefix, suffix, and search tests that the surrogate had nothing
to do with.

For module specifiers, `import "../\uD800"` was not a parent import,
`import "node:\uD800"` was not a Node.js module, `import "/\uD800"` was
not absolute, `"./\uD800.d.ts"` was not a declaration file,
`"./__mocks__/\uD800"` did not contain a mocks directory, and
`require("\uD800")` was classified as computed. The mock factory rules
dropped their diagnostic together with the fix, and yoda's range exception
compared the bounds as bytes and could not see a surrogate range at all.

For other values, `aria-proptypes` reported a surrogate string as an
invalid string, `jsx-key` never saw duplicate surrogate keys,
`jsx-no-target-blank` treated such links as internal and ignored the `rel`
tokens beside them, and the redundant-alt, namespace, console-space, Vue
casing, and ternary checks were skipped.

The same gate also sat in front of user-configured patterns: the `allow`
regexes of `no-require-imports` and the `allowedSnapshots` matchers of
`no-large-snapshots` were only consulted when the value converts to UTF-8,
so a surrogate-containing import path or snapshot name was always
reported, even when a configured pattern matches it. The same policy now covers every reachable configured pattern: valid-title's disallowedWords and mustMatch checks, vue prop-name-casing's ignoreProps, and no-unassigned-import's allow globs all match through the lossy text. jsx-key formats numeric keys with ECMAScript Number::toString, matching the runtime attribute value.

Run these checks on the JavaScript value. Prefix, suffix, containment, and
separator tests use the `JSStr` search methods; path components, `../`
prefixes, word scans, and token scans walk code units or code points, where
a lone surrogate is a boundary that matches nothing; the yoda range bounds
compare by UTF-16 code unit as JavaScript does; duplicate keys and ternary
member names compare `JSStr` values. The Vue casing predicates take `JSStr`
directly, and `static_string_value` builds its result in the arena so
concatenations keep surrogate pairs. Fixes that must write the name as Rust
text are declined for such values while the diagnostic is still reported,
with the name shown in its escaped Debug spelling. `new-cap` treats a name
starting with a lone surrogate as non-alphabetic, matching how
`toUpperCase` leaves it unchanged, and `require-unicode-regexp` still sees
a `u` flag beside one. Configured patterns match against a copy in which
each lone surrogate half is the replacement character U+FFFD; patterns
from configuration are always valid UTF-8 because serde_json rejects
lone-surrogate escapes, so this agrees with ESLint's UTF-16 matching for
every expressible pattern except one that literally matches the
replacement character.

Part of #26242.

Implemented with AI assistance.
Static property names borrow AST strings but can also own numeric or
regular-expression conversions. Give that API a dedicated type so
`PropertyKey::static_name`, `PropertyKey::name`, and
`ClassElement::static_name` return the complete JavaScript name instead
of `None` for a key containing a lone surrogate.

`StaticPropertyName` borrows `JSStr` for identifier, string, and template keys
and owns the UTF-8 text of numeric and regular-expression keys. Numeric
keys convert with ECMAScript `Number::toString`, so `1e21` gets the name
`"1e+21"` like the runtime property key. Equal names compare and hash
equally across both forms, and consumers request a UTF-8 view explicitly
where they need a Rust string.

This is re-cut on the migrated AST, so the earlier UTF-8 adapters are
gone and the consumers that key on property identity use the complete
name. Duplicate keys, class members, overload signatures, accessor
pairs, sorted keys, the semantic class table, declaration accessor
inference, and React display names for object properties now handle
surrogate names. Fixed-name lookups and fixes that must emit
identifiers still convert to UTF-8 and decline otherwise. Diagnostics escape a surrogate name once and in one spelling: the Display and Debug forms both print lowercase \udXXX escapes, matching printed output.

Part of #26242.

Implemented with AI assistance.
The JSON string serializer kept an `EscapeTable` trait with one
implementation after the JSStr migration removed the marker decoder that
had justified it. The indirection no longer selects anything.

Use the `ESCAPE` lookup table directly, make `get_escapes_mask` a free
function with the same algorithm and mask contract, and drop the type
parameter from `write_str`. Output is unchanged.

Part of #26242.

Implemented with AI assistance.
`EncodeUtf16` reported no size hint, so collecting code units into a
`Vec<u16>` on the N-API and codegen paths grew the buffer incrementally.

Report a lower bound of one unit per three WTF-8 bytes and an upper bound
of one unit per byte, plus any buffered trailing surrogate. Check the
bounds at every step over ASCII, multi-byte, lone-surrogate and paired
inputs.

Part of #26242.

Implemented with AI assistance.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-ast Area - AST definitions and visitors, oxc_ast / oxc_ast_visit A-linter Area - Linter (oxlint): rules, config, diagnostics, fixes. Add L-* labels for details

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant