Skip to content

feat(string): implement RopeString with thin vtable and lazy flattening - #5006

Open
akash-R-A-J wants to merge 23 commits into
boa-dev:mainfrom
akash-R-A-J:feat/rope-strings
Open

akash-R-A-J wants to merge 23 commits into
boa-dev:mainfrom
akash-R-A-J:feat/rope-strings

Conversation

@akash-R-A-J

@akash-R-A-J akash-R-A-J commented Mar 11, 2026 •

Copy link
Copy Markdown
Contributor

This Pull Request fixes/closes #5005 .

This PR introduces Rope strings to boa_string and integrates them into the engine’s concatenation pipeline to eliminate the pathological O(N²) behavior of repeated string concatenation.

Key Changes

Rope Strings

  • Added RopeString representation (core/string/src/vtable/rope.rs)
  • Lazy flattening: ropes are only flattened when a contiguous buffer is required
  • Balanced tree construction for batch concatenations
  • Fibonacci-based rope rebalancing to maintain bounded depth
  • Leaf sinking optimization to reduce rope node depth during concatenation
  • Depth limit (32) and small-string threshold to avoid pathological trees
  • Iterative traversal to prevent recursion overflow
  • Devirtualized hot paths (clone, drop, as_str, code_unit_at)

Engine Integration

  • JsValue::add now creates ropes for large concatenations (len(lhs) + len(rhs) > 1024)
  • ConcatToString updated to use balanced batch concatenation
  • String.prototype.concat refactored to use the new API

Thin VTable & Performance Recovery

  • Moved method pointers to static vtables, reducing string header size
  • Devirtualized hot paths (clone, drop, as_str, code_unit_at)
  • Added cached u64 hash to speed up property lookups
  • Added ptr_eq + hash checks to optimize equality comparisons

Benchmarks

Concatenation Stress Test

main : 2.876 s ±  0.025 s
rope : 132.4 ms ±   0.3 ms

≈ 21.7× faster

V8 Combined Suite

main : 181.562 s ±  8.539 s
rope : 181.642 s ±  9.381 s

Summary

This change removes quadratic concatenation behavior while maintaining baseline performance for general workloads. The thin vtable and devirtualization ensure that ropes introduce minimal overhead when not used.

@akash-R-A-J
akash-R-A-J requested a review from a team as a code owner March 11, 2026 23:58
@codecov

codecov Bot commented Mar 12, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 43.76812% with 388 lines in your changes missing coverage. Please review.
✅ Project coverage is 62.66%. Comparing base (6ddc2b4) to head (3a16e53).
⚠️ Report is 1090 commits behind head on main.

Files with missing lines Patch % Lines
core/string/src/iter.rs 25.80% 115 Missing ⚠️
core/string/src/vtable/rope.rs 33.52% 113 Missing ⚠️
core/string/src/str.rs 38.39% 69 Missing ⚠️
core/string/src/lib.rs 66.46% 56 Missing ⚠️
cli/src/debug/string.rs 0.00% 8 Missing ⚠️
core/string/src/vtable/slice.rs 61.90% 8 Missing ⚠️
core/engine/src/builtins/regexp/mod.rs 25.00% 6 Missing ⚠️
core/engine/src/builtins/date/utils.rs 20.00% 4 Missing ⚠️
core/string/src/vtable/static.rs 62.50% 3 Missing ⚠️
core/engine/src/builtins/number/globals.rs 50.00% 2 Missing ⚠️
... and 2 more
Additional details and impacted files
@@             Coverage Diff             @@
##             main    #5006       +/-   ##
===========================================
+ Coverage   47.24%   62.66%   +15.42%     
===========================================
  Files         476      540       +64     
  Lines       46892    59053    +12161     
===========================================
+ Hits        22154    37007    +14853     
+ Misses      24738    22046     -2692     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Comment thread core/string/src/vtable/mod.rs Resolved
Comment thread core/string/src/vtable/rope.rs Resolved
Comment thread core/string/src/lib.rs Outdated
// SAFETY: Caller must ensure the type matches.
unsafe { self.ptr.cast::<T>().as_ref() }
#[must_use]
pub fn as_str(&self) -> JsStr<'static> {

@jedel1043 jedel1043 Mar 12, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is unsound. It's returning a 'static reference to a temporary JsString, so you could deallocate the original string and the compiler will happily let you access the JsStr<'static>:

let s = JsString::from_str("undefined behaviour!");
let temp = s.as_str();
drop(s)
println!("{}", temp.display_lossy()); // UB!

@akash-R-A-J akash-R-A-J Mar 12, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for pointing this out! you're absolutely right, that was a leftover from the initial pointer-based POC while focusing on the memory layout. I've now refactored the vtable to use HRTBs for as_str which replaces that temporary shim with a lifetime binding. It was my fault.

@zhuzhu81998 zhuzhu81998 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ci shows segmentaion fault (potential cause below)

let specifier = specifier.cow_replace('/', "\\");

let short_path = Path::new(&specifier);
let short_path = Path::new(&*specifier);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what does this have to do with rope strings?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

still a problem

pub(crate) mod rope;
pub(crate) use rope::RopeString;

/// Header for all `JsString` allocations.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Then call this JsStringHeader instead of RawJsString perhaps?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sounds good, will replace RawJsString with the suggested JsStringHeader

Comment thread core/string/src/vtable/mod.rs Outdated
Comment on lines +37 to +39
unsafe impl Sync for RawJsString {}
// SAFETY: RawJsString contains only thread-safe data.
unsafe impl Send for RawJsString {}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do you need this somewhere?

Comment thread core/string/src/vtable/mod.rs Outdated
Comment on lines +60 to +63
// SAFETY: We only mutate refcount and hash via atomic-casts when kind != Static.
unsafe impl Sync for JsStringVTable {}
// SAFETY: JsStringVTable contains only thread-safe data.
unsafe impl Send for JsStringVTable {}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same question: where is the need?

Comment on lines +61 to +70
/// A rope string that is a tree of other strings.
#[repr(C)]
pub(crate) struct RopeString {
/// Standardized header for all strings.
pub(crate) header: RawJsString,
pub(crate) left: JsString,
pub(crate) right: JsString,
flattened: OnceCell<JsString>,
pub(crate) depth: u8,
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmmm so it is my understanding that JsString here will most likely GC-tracked. And there is no way for GC to know that RopeString is holdig reference to the left and right here?
are yo doing something to prevent this?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To clarify: JSStrings are not GC-tracked, they're independently ref-counted, so it's fine to not trace through them. I'm fairly certain the UB comes from the modifications made to as_str that removed the lifetime inheritance for JsStr<'static>.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

indeed its not gc. disabling the gc does not resolve the segmentation fault XD.

@github-actions

github-actions Bot commented Mar 14, 2026 •

Copy link
Copy Markdown

Test262 conformance changes

Test result main count PR count difference
Total 52,963 52,963 0
Passed 50,073 50,063 -10
Ignored 2,072 2,072 0
Failed 818 828 +10
Panics 0 0 0
Conformance 94.54% 94.52% -0.02%
Broken tests (10):
test/built-ins/parseFloat/S15.1.2.3_A2_T1.js (previously Passed)
test/built-ins/parseFloat/S15.1.2.3_A2_T7.js (previously Passed)
test/built-ins/parseFloat/S15.1.2.3_A2_T8.js (previously Passed)
test/built-ins/parseFloat/S15.1.2.3_A2_T6.js (previously Passed)
test/built-ins/parseFloat/S15.1.2.3_A2_T4.js (previously Passed)
test/built-ins/parseFloat/S15.1.2.3_A2_T3.js (previously Passed)
test/built-ins/parseFloat/S15.1.2.3_A2_T10.js (previously Passed)
test/built-ins/parseFloat/S15.1.2.3_A2_T5.js (previously Passed)
test/built-ins/parseFloat/S15.1.2.3_A2_T2.js (previously Passed)
test/built-ins/parseFloat/S15.1.2.3_A2_T9.js (previously Passed)

Tested main commit: 197b736bb87523a14b41834c078adbec3059d237
Tested PR commit: af923c75d12138009f1d7dc46a8106c310998475
Compare commits: 197b736...af923c7

Comment thread core/string/src/vtable/rope.rs Resolved
@akash-R-A-J
akash-R-A-J requested a review from jedel1043 March 14, 2026 02:23
@akash-R-A-J

Copy link
Copy Markdown
Contributor Author

@jedel1043 I believe all requested changes have now been addressed. CI is green across all platforms, and test262 results match main.

Please let me know if anything else needs adjustment.

@github-actions github-actions Bot added Waiting On Review Waiting on reviews from the maintainers C-Tests Issues and PRs related to the tests. C-Builtins PRs and Issues related to builtins/intrinsics C-VM Issues and PRs related to the Boa Virtual Machine. and removed Waiting On Review Waiting on reviews from the maintainers labels Mar 15, 2026
@github-actions github-actions Bot added the Waiting On Review Waiting on reviews from the maintainers label Mar 15, 2026
Comment thread core/string/src/vtable/rope.rs Resolved
@akash-R-A-J
akash-R-A-J requested a review from jedel1043 March 15, 2026 03:23
@akash-R-A-J
akash-R-A-J requested a review from nekevss as a code owner March 15, 2026 14:59
@github-actions github-actions Bot added C-CLI Issues and PRs related to the Boa command line interface. C-Intl Changes related to the `Intl` implementation C-Runtime Issues and PRs related to Boa's runtime features labels Mar 15, 2026
@jedel1043 jedel1043 added the A-Performance Performance related changes and issues label Mar 17, 2026
@akash-R-A-J

Copy link
Copy Markdown
Contributor Author

Hey @jedel1043, whenever you have some time, could you please take another look at this PR?

All previously mentioned issues should now be addressed, including the rope rebalancing changes, safety fixes, and flattening adjustments discussed in the earlier review.

Here's the latest benchmark results:

final_benchmark_rope

@jedel1043 jedel1043 removed the C-Builtins PRs and Issues related to builtins/intrinsics label Mar 20, 2026
@github-actions github-actions Bot added the C-Builtins PRs and Issues related to builtins/intrinsics label Mar 22, 2026
@github-actions

github-actions Bot commented Mar 22, 2026 •

Copy link
Copy Markdown

Test262 conformance changes

Test result main count PR count difference
Total 53,578 53,578 0
Passed 51,457 51,457 0
Ignored 1,629 1,629 0
Failed 492 492 0
Panics 0 0 0
Conformance 96.04% 96.04% 0.00%

Tested main commit: 2d8a534c683d386144d202e88e642c7e09382e01
Tested PR commit: 3a16e537b7e8c4fb1eea193e489902e8c95e7884
Compare commits: 2d8a534...3a16e53

@github-actions github-actions Bot added C-WebAssembly Anything related to using Boa with Wasm C-FFI Foreign Function Interface, to be able to use Boa from a different language, such as C labels Nov 18, 2026
@github-actions github-actions Bot added the C-Actions Pull requests that update Github Actions code label Nov 18, 2026
@akash-R-A-J

Copy link
Copy Markdown
Contributor Author

@jedel1043 @nekevss

The Check SemVer compatibility CI job failed for boa_string against published v0.22.0 due to 3 API differences introduced by the rope string architecture:

  1. JsStr changed from struct to enum: Converted to enum JsStr<'a> { Latin1(&'a [u8]), Utf16(&'a [u16]), Rope(RopeSlice<'a>) } to support borrowed, lazy views into rope strings without flattening.

  2. JsStrVariant removed: Previously wrapped by struct JsStr; made redundant once JsStr itself became the enum.

  3. RawJsString renamed: Renamed to JsStringHeader per earlier review discussion.

What is needed:
Because JsStr turning into an enum is an intentional breaking change for the next release (v0.23.0), cargo-semver-checks flags it since the workspace package version is still 0.22.0.

To address this cleanly, I have:

  • Added backwards-compatible type aliases for downstream callers (pub type RawJsString = JsStringHeader and pub type JsStrVariant<'a> = JsStr<'a>).
  • Marked boa_string to be excluded in .github/workflows/rust.yml (similar to boa_wintertc in feat: add boa_wintertc crate skeleton for WinterTC compliance #5105) until the workspace version bump for 0.23.0.

Could you confirm if excluding boa_string from cargo-semver-checks is the preferred approach here until release bump, or if there is an alternative convention you'd prefer?

@jedel1043

Copy link
Copy Markdown
Member

Just bump the version; we'll be releasing 0.23 this month anyways

@github-actions github-actions Bot added the C-Dependencies Pull requests that update a dependency file label Nov 23, 2026
@akash-R-A-J

Copy link
Copy Markdown
Contributor Author

@jedel1043
Bumped workspace version to 0.23.0, resolved the merge conflict with main, and re-enabled the SemVer check without exclusions. All CI checks are now fully green across all platforms.

@zhuzhu81998 zhuzhu81998 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

a few comments on the general side.
not yet checked the concrete implementation.

also, maybe an updated performance comparison for a final version would be nice.

Comment thread ffi/wasm/tests/web.rs
unused_crate_dependencies,
reason = "https://github.com/rust-lang/rust/issues/95513"
)]
#![allow(unused_crate_dependencies)]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what is this change for?

Comment thread core/string/src/type.rs Outdated
/// that should not leak through the API.
#[allow(private_interfaces)]
pub(crate) trait InternalStringType: StringType {
pub trait InternalStringType: StringType {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you are making this internal type public?

let specifier = specifier.cow_replace('/', "\\");

let short_path = Path::new(&specifier);
let short_path = Path::new(&*specifier);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

still a problem

}

false
self.shape.lookup(key).is_some()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks like a valid change but still, unrelated to RopeStrings?

Comment thread core/runtime/src/text/encodings.rs Outdated
use boa_engine::string::JsStr;
use boa_engine::{JsString, js_string};

#[allow(dead_code)]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why?

Comment thread core/string/src/vtable/rope.rs Outdated

/// Fibonacci numbers for rope balancing thresholds.
/// `F(n) = Fib(n + 2)`. A rope of depth `n` is balanced if its length >= `F(n)`.
static FIBONACCI_THRESHOLDS: [u32; 46] = [

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use a const fn which is evaluated at comptime instead of hardcoding might be more idiomatic

Comment thread core/runtime/src/text/encodings.rs Outdated
use boa_engine::string::JsStr;
use boa_engine::{JsString, js_string};

#[allow(dead_code)]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

again, why dead code?

Comment thread core/string/src/lib.rs Outdated
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
#[repr(u8)]
pub(crate) enum JsStringKind {
pub enum JsStringKind {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also, visibility change really necessary?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-Performance Performance related changes and issues C-Actions Pull requests that update Github Actions code C-Builtins PRs and Issues related to builtins/intrinsics C-CLI Issues and PRs related to the Boa command line interface. C-Dependencies Pull requests that update a dependency file C-FFI Foreign Function Interface, to be able to use Boa from a different language, such as C C-Intl Changes related to the `Intl` implementation C-Runtime Issues and PRs related to Boa's runtime features C-Tests Issues and PRs related to the tests. C-VM Issues and PRs related to the Boa Virtual Machine. C-WebAssembly Anything related to using Boa with Wasm Waiting On Author Waiting on PR changes from the author

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Optimize string concatenation by introducing Rope strings

5 participants