Skip to content

Commit 15cd5e5

Browse files
authored
perf(runtime): shrink ada, parse URLs once, fix URLPattern groups (#2152)
### Description Stacked on #2134 (Ada 4.1.1). This is the Android half of NativeScript/ios#606. As #2134 stands, the upgrade adds about 89 KB per ABI to `libNativeScript.so`. This PR takes back most of that. **1. Build ada at `-Os`.** ada was compiled at the runtime-wide `-O3`. At `-Os`, ada's code is about 50 KB smaller per ABI. Native benchmark on two phones (median of 3 rounds, ns per operation): | | Galaxy S20 FE `-O3` | `-Os` | Galaxy S8 `-O3` | `-Os` | |---|---|---|---|---| | absolute URL parse | 192 | 214 (+11%) | 441 | 519 (+18%) | | relative URL parse | 130 | 154 (+19%) | 336 | 388 (+15%) | | IDN host parse | 1027 | 1097 (+7%) | 2203 | 2352 (+7%) | | URLSearchParams | 609 | 599 (−2%) | 1408 | 1360 (−3%) | The slowdown is tens of nanoseconds per `new URL()`. Only `ada.cpp` changes; the rest of the runtime stays at `-O3`, and local Debug builds are unaffected. **2. Parse each URL once.** - `new URL(input, base)` called `ada::can_parse(input, &base)`, which parses both, then parsed both again. It now parses each once. - `URL.canParse` uses `ada::parse` as well, so `ada::can_parse` and its second parser instantiation are no longer linked. - These fixes ride along: - `canParse` stringifies its arguments instead of casting them to `v8::String` unchecked, so `URL.canParse(urlObject)` no longer reads a non-string as a string; - `canParse` treats an undefined base as absent and no longer truncates at an embedded NUL; - `new URL()` without arguments throws a `TypeError` instead of reading `undefined` as a string; - a base object whose `toString()` throws now propagates the exception instead of aborting in `ToLocalChecked()`. **3. URLPattern capture groups and `hasRegExpGroups`.** Found while adding specs: `testURLPattern.js` was never `require`d from `mainpage.js`, so the Android URLPattern specs never ran. Once registered, they exposed two bugs: - `v8_regex_provider::regex_search` returned `RegExp.exec`'s whole match as the first capture. Every named group read its predecessor's value, so `:id` in `/books/:id` got `/books/123`. ada also received one more result than it has group names. iOS already skips element 0. - The `hasRegExpGroups` getter was registered as `hasRegexpGroups`. Both now match iOS, and the specs now cover `test()`/`exec()` with capture groups. **Size.** arm64 `optimized` build. Numbers are loaded bytes from the `lld` link map (code, rodata, data, unwind), because stripped `.so` sizes are page-rounded. | | ada | whole `libNativeScript.so` | |---|---|---| | main (ada 4.0.0) | 297.7 KB | 26,285,061 | | #2134 (ada 4.1.1) | 391.8 KB | 26,374,175 | | this PR | 307.2 KB | 26,290,495 (−83.7 KB vs #2134) | | this PR + `-fdata-sections` from #2136 | 250.9 KB | 26,233,370 (−140.8 KB vs #2134, −51.7 KB vs main) | **Not ported from iOS:** - **Symbol visibility.** The iOS PR's biggest saving was hiding ada's symbols. Android already builds with `-fvisibility=hidden` and a version script. The equivalent loss here came from `-fno-data-sections`: it put every ada vtable in one section, so unused code like the `ada::url` parser stayed linked. #2136 removes that flag. - **System ICU for IDNA.** The NDK's `libicu.so` exists only from API 31 and ships no `uidna.h`. The only system UTS #46 is Java's `android.icu.text.IDNA` (API 24+, ICU 56 / Unicode 8 at the bottom of the range), which would need JNI. Left out. - **`std::regex`.** The Android runtime has no `std::regex` use; URLPattern already runs on V8's RegExp. ### Does your commit message include the wording below to reference a specific issue in this repo? No. ### Related Pull Requests - #2134, the base of this PR - #2136, which removes `-fno-data-sections`; together they reach the last size row above - NativeScript/ios#606, the iOS counterpart ### Does your pull request have unit tests? Yes. The full suite passes on an API 36 arm64 emulator: 1,792 specs, 0 failures. `testURLPattern.js` now runs, and new specs cover: - relative URLs against string and `URL` bases; - invalid bases; - a throwing base `toString()`; - `new URL()` without arguments; - `URL.canParse` with string, `URL`-object and undefined arguments; - IDN hosts (Unicode, uppercase `xn--`, ZWJ rejection); - non-ASCII URLPattern group names; - URLPattern `test()`/`exec()` with capture groups. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit - **Bug Fixes** - Improved URL construction and validation, including relative URLs, base handling, and internationalized hostnames. - Updated `URL.canParse()` to validate inputs and optional bases consistently. - Corrected URLPattern capture-group results and the exposed `hasRegExpGroups` property name. - **Tests** - Added coverage for URL parsing, validation, internationalized hostnames, and URLPattern matching and captures. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
1 parent 4dbef6a commit 15cd5e5

6 files changed

Lines changed: 133 additions & 72 deletions

File tree

‎test-app/app/src/main/assets/app/mainpage.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@ require("./tests/testPostFrameCallback");
113113
require("./tests/testPerformance");
114114
require("./tests/console/logTests.js");
115115
require('./tests/testURLImpl.js');
116+
require('./tests/testURLPattern.js');
116117
require('./tests/testURLSearchParamsImpl.js');
117118
require('./tests/testQueueMicrotask');
118119
require('./tests/testErrorEvents');

‎test-app/app/src/main/assets/app/tests/testURLImpl.js‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,5 +58,57 @@ describe("URL", function () {
5858
expect(url.searchParams.get("q")).toBe("hello");
5959
expect(url.pathname).toBe("/some/path");
6060
});
61+
62+
it("throws a TypeError without arguments", function () {
63+
expect(() => new URL()).toThrowError(TypeError);
64+
});
65+
66+
it("resolves a relative URL against a string base", function () {
67+
const url = new URL("../c?d=1#e", "https://a.test/x/y/z");
68+
expect(url.href).toBe("https://a.test/x/c?d=1#e");
69+
});
70+
71+
it("resolves a relative URL against a URL object base", function () {
72+
const url = new URL("page", new URL("https://a.test/dir/"));
73+
expect(url.href).toBe("https://a.test/dir/page");
74+
});
75+
76+
it("throws a TypeError for an invalid base", function () {
77+
expect(() => new URL("page", "not a url")).toThrowError(TypeError);
78+
});
79+
80+
it("throws a TypeError when the input does not parse against the base", function () {
81+
expect(() => new URL("http://[", "https://a.test/")).toThrowError(TypeError);
82+
});
83+
84+
it("propagates an exception thrown by the base's toString", function () {
85+
const base = {
86+
toString() {
87+
throw new Error("base toString");
88+
},
89+
};
90+
expect(() => new URL("page", base)).toThrowError("base toString");
91+
});
92+
93+
it("canParse agrees with the constructor", function () {
94+
expect(URL.canParse("https://a.test/")).toBe(true);
95+
expect(URL.canParse("not a url")).toBe(false);
96+
expect(URL.canParse("page", "https://a.test/dir/")).toBe(true);
97+
expect(URL.canParse("page", "not a url")).toBe(false);
98+
expect(URL.canParse("http://[", "https://a.test/")).toBe(false);
99+
});
100+
101+
it("canParse stringifies its arguments and ignores an undefined base", function () {
102+
expect(URL.canParse(new URL("https://a.test/x"))).toBe(true);
103+
expect(URL.canParse("page", new URL("https://a.test/dir/"))).toBe(true);
104+
expect(URL.canParse("https://a.test/", undefined)).toBe(true);
105+
});
106+
107+
it("converts internationalized hostnames to ASCII", function () {
108+
expect(new URL("https://B\u00FCcher.example/").hostname).toBe("xn--bcher-kva.example");
109+
expect(new URL("https://\u4F8B\u3048.\u30C6\u30B9\u30C8/").hostname).toBe("xn--r8jz45g.xn--zckzah");
110+
expect(new URL("https://XN--BCHER-KVA.example/").hostname).toBe("xn--bcher-kva.example");
111+
expect(() => new URL("https://a\u200Db.example/")).toThrowError(TypeError);
112+
});
61113
});
62114

‎test-app/app/src/main/assets/app/tests/testURLPattern.js‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,17 @@ describe("URLPattern", function () {
3434
});
3535

3636

37+
it("accepts non-ASCII group names", function () {
38+
const pattern = new URLPattern({ pathname: "/:caf\u00E9/:\u540D\u524D" });
39+
const result = pattern.exec({ pathname: "/a/b" });
40+
expect(result.pathname.groups["caf\u00E9"]).toBe("a");
41+
expect(result.pathname.groups["\u540D\u524D"]).toBe("b");
42+
});
43+
44+
it("rejects a group name that does not start with an identifier start", function () {
45+
expect(() => new URLPattern({ pathname: "/:\u0663x" })).toThrowError(TypeError);
46+
});
47+
3748
it("parses with undefined base", function () {
3849
const pattern = new URLPattern("https://google.com", undefined);
3950
expect(pattern.protocol).toBe("https");
@@ -46,4 +57,22 @@ describe("URLPattern", function () {
4657
expect(pattern.hostname).toBe("google.com");
4758
});
4859

60+
it("test() matches a URL against a pattern with a capture group", function () {
61+
const pattern = new URLPattern("https://example.com/books/:id");
62+
expect(pattern.test("https://example.com/books/123")).toBe(true);
63+
expect(pattern.test("https://example.com/movies/123")).toBe(false);
64+
});
65+
66+
it("exec() extracts named capture groups", function () {
67+
const pattern = new URLPattern("https://example.com/books/:id");
68+
const result = pattern.exec("https://example.com/books/123");
69+
expect(result).not.toBeNull();
70+
expect(result.pathname.input).toBe("/books/123");
71+
expect(result.pathname.groups.id).toBe("123");
72+
});
73+
74+
it("exec() returns null when the URL does not match", function () {
75+
const pattern = new URLPattern("https://example.com/books/:id");
76+
expect(pattern.exec("https://example.com/movies/123")).toBeNull();
77+
});
4978
});

‎test-app/runtime/CMakeLists.txt‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,9 @@ if (OPTIMIZED_BUILD OR OPTIMIZED_WITH_INSPECTOR_BUILD OR NOT CMAKE_BUILD_TYPE ST
142142
# (Debug). AGP builds the release variant as RelWithDebInfo, whose default -O2 would
143143
# otherwise win.
144144
string(APPEND CMAKE_CXX_FLAGS_RELWITHDEBINFO " -O3")
145+
# ada at -Os instead of -O3: about 50 KB less per ABI for URL parses that
146+
# are 7-19% (tens of nanoseconds) slower.
147+
set_source_files_properties(src/main/cpp/ada/ada.cpp PROPERTIES COMPILE_OPTIONS "-Os")
145148
else ()
146149
string(APPEND CMAKE_CXX_FLAGS " ${COMMON_CMAKE_ARGUMENTS} -g")
147150
endif ()

‎test-app/runtime/src/main/cpp/URLImpl.cpp‎

Lines changed: 44 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,12 @@
44

55
#include "URLImpl.h"
66

7+
#include <optional>
8+
79
using namespace tns;
810
using namespace ada;
911

10-
URLImpl::URLImpl(url_aggregator url) : url_(url) {}
12+
URLImpl::URLImpl(url_aggregator url) : url_(std::move(url)) {}
1113

1214
URLImpl *URLImpl::GetPointer(v8::Local<v8::Object> object) {
1315
if (object->InternalFieldCount() < 1) {
@@ -90,85 +92,48 @@ void URLImpl::Ctor(const v8::FunctionCallbackInfo<v8::Value> &args) {
9092
auto value = args[0];
9193
auto isolate = args.GetIsolate();
9294
auto context = isolate->GetCurrentContext();
93-
if (count >= 1 && !value->IsString()) {
95+
if (count < 1 || !value->IsString()) {
9496
isolate->ThrowException(
9597
v8::Exception::TypeError(v8::String::Empty(isolate)));
9698
return;
9799
}
98100

99-
url_aggregator url;
100-
101101
auto url_string = ArgConverter::ConvertToString(args[0].As<v8::String>());
102102

103+
std::optional<std::string> base_string;
103104
if (count > 1) {
104105
if (args[1]->IsString()) {
105-
auto base_string = ArgConverter::ConvertToString(args[1].As<v8::String>());
106-
std::string_view base_string_view(base_string.data(), base_string.length());
107-
108-
if (!can_parse(url_string, &base_string_view)) {
109-
isolate->ThrowException(
110-
v8::Exception::TypeError(v8::String::Empty(isolate)));
111-
return;
112-
}
113-
auto base_url = ada::parse<ada::url_aggregator>(base_string_view, nullptr);
114-
115-
auto result = ada::parse<ada::url_aggregator>(url_string, &base_url.value());
116-
117-
if (result) {
118-
url = result.value();
119-
} else {
120-
isolate->ThrowException(
121-
v8::Exception::TypeError(v8::String::Empty(isolate)));
122-
return;
123-
}
106+
base_string = ArgConverter::ConvertToString(args[1].As<v8::String>());
124107
} else if (args[1]->IsObject()) {
125-
auto base_string = ArgConverter::ConvertToString(
126-
args[1]->ToString(context).ToLocalChecked());
127-
std::string_view base_string_view(base_string.data(), base_string.length());
128-
if (!can_parse(std::string_view(url_string.data(), url_string.length()),
129-
&base_string_view)) {
130-
isolate->ThrowException(
131-
v8::Exception::TypeError(v8::String::Empty(isolate)));
108+
v8::Local<v8::String> base;
109+
if (!args[1]->ToString(context).ToLocal(&base)) {
132110
return;
133111
}
112+
base_string = ArgConverter::ConvertToString(base);
113+
}
114+
// Any other 2nd argument is treated as undefined.
115+
}
134116

135-
136-
auto base_url = ada::parse<ada::url_aggregator>(base_string_view, nullptr);
137-
138-
auto result = ada::parse<ada::url_aggregator>(url_string, &base_url.value());
139-
140-
if (result) {
141-
url = result.value();
142-
} else {
143-
isolate->ThrowException(
144-
v8::Exception::TypeError(v8::String::Empty(isolate)));
145-
return;
146-
}
147-
} else {
148-
// treat 2nd arg as undefined otherwise.
149-
auto result = ada::parse<ada::url_aggregator>(url_string, nullptr);
150-
if (result) {
151-
url = result.value();
152-
} else {
153-
isolate->ThrowException(
154-
v8::Exception::TypeError(v8::String::Empty(isolate)));
155-
return;
156-
}
117+
auto parse = [&]() {
118+
if (!base_string) {
119+
return ada::parse<url_aggregator>(url_string, nullptr);
157120
}
158-
} else {
159-
auto result = ada::parse<ada::url_aggregator>(url_string, nullptr);
160-
if (result) {
161-
url = result.value();
162-
} else {
163-
isolate->ThrowException(
164-
v8::Exception::TypeError(v8::String::Empty(isolate)));
165-
return;
121+
auto base = ada::parse<url_aggregator>(*base_string, nullptr);
122+
if (!base) {
123+
return base;
166124
}
125+
return ada::parse<url_aggregator>(url_string, &base.value());
126+
};
127+
auto result = parse();
128+
if (!result) {
129+
isolate->ThrowException(
130+
v8::Exception::TypeError(v8::String::Empty(isolate)));
131+
return;
167132
}
168133

169134
auto ret = args.This();
170135

171-
auto urlImpl = new URLImpl(url);
136+
auto urlImpl = new URLImpl(std::move(result.value()));
172137

173138

174139
ret->SetAlignedPointerInInternalField(0, urlImpl, v8::kEmbedderDataTypeTagDefault);
@@ -495,17 +460,26 @@ void URLImpl::ToString(const v8::FunctionCallbackInfo<v8::Value> &info) {
495460

496461

497462
void URLImpl::CanParse(const v8::FunctionCallbackInfo<v8::Value> &info) {
463+
// ada::parse rather than ada::can_parse: the constructor already links it,
464+
// and can_parse pulls in a second instantiation of ada's parser.
465+
auto isolate = info.GetIsolate();
466+
auto context = isolate->GetCurrentContext();
467+
v8::Local<v8::String> input;
468+
if (!info[0]->ToString(context).ToLocal(&input)) {
469+
return;
470+
}
471+
auto url_string = ArgConverter::ConvertToString(input);
498472
bool value;
499-
auto count = info.Length();
500-
501-
502-
if (count > 1) {
503-
auto url_string = ArgConverter::ConvertToString(info[0].As<v8::String>());
504-
auto base_string = ArgConverter::ConvertToString(info[1].As<v8::String>());
505-
std::string_view base_string_view(base_string.data(), base_string.length());
506-
value = can_parse(url_string, &base_string_view);
473+
if (info.Length() > 1 && !info[1]->IsUndefined()) {
474+
v8::Local<v8::String> base_input;
475+
if (!info[1]->ToString(context).ToLocal(&base_input)) {
476+
return;
477+
}
478+
auto base = ada::parse<url_aggregator>(
479+
ArgConverter::ConvertToString(base_input), nullptr);
480+
value = base && ada::parse<url_aggregator>(url_string, &base.value());
507481
} else {
508-
value = can_parse(ArgConverter::ConvertToString(info[0].As<v8::String>()).c_str(), nullptr);
482+
value = ada::parse<url_aggregator>(url_string, nullptr).has_value();
509483
}
510484

511485
info.GetReturnValue().Set(value);

‎test-app/runtime/src/main/cpp/URLPatternImpl.cpp‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,9 @@ v8_regex_provider::regex_search(std::string_view input,
6969
auto array = matches.As<v8::Array>();
7070
auto len = array->Length();
7171
ret.reserve(len);
72-
for (int i = 0; i < len; i++) {
72+
// Element 0 is the whole match. ada pairs exec_result[i] with
73+
// group_name_list[i], so it expects only the capture groups.
74+
for (uint32_t i = 1; i < len; i++) {
7375
v8::Local<v8::Value> item;
7476
if (!array->Get(isolate->GetCurrentContext(), i).ToLocal(&item)) {
7577
return std::nullopt;
@@ -146,7 +148,7 @@ v8::Local<v8::FunctionTemplate> URLPatternImpl::GetCtor(v8::Isolate *isolate) {
146148
v8::FunctionTemplate::New(isolate, &Exec));
147149

148150
tmpl->SetLazyDataProperty(
149-
ArgConverter::ConvertToV8String(isolate, "hasRegexpGroups"),
151+
ArgConverter::ConvertToV8String(isolate, "hasRegExpGroups"),
150152
GetHasRegexpGroups);
151153

152154
tmpl->SetLazyDataProperty(

0 commit comments

Comments
 (0)