Ada 3.3.0
Fast spec-compliant URL parser
Loading...
Searching...
No Matches
url_pattern_helpers.cpp
Go to the documentation of this file.
1#if ADA_INCLUDE_URL_PATTERN
3
4#include <algorithm>
5#include <optional>
6#include <string>
7
8namespace ada::url_pattern_helpers {
9
10std::tuple<std::string, std::vector<std::string>>
11generate_regular_expression_and_name_list(
12 const std::vector<url_pattern_part>& part_list,
13 url_pattern_compile_component_options options) {
14 // Let result be "^"
15 std::string result = "^";
16
17 // Let name list be a new list
18 std::vector<std::string> name_list{};
19
20 // For each part of part list:
21 for (const url_pattern_part& part : part_list) {
22 // If part's type is "fixed-text":
23 if (part.type == url_pattern_part_type::FIXED_TEXT) {
24 // If part's modifier is "none"
25 if (part.modifier == url_pattern_part_modifier::none) {
26 // Append the result of running escape a regexp string given part's
27 // value
28 result += escape_regexp_string(part.value);
29 } else {
30 // A "fixed-text" part with a modifier uses a non capturing group
31 // (?:<fixed text>)<modifier>
32 // Append "(?:" to the end of result.
33 result.append("(?:");
34 // Append the result of running escape a regexp string given part's
35 // value to the end of result.
36 result.append(escape_regexp_string(part.value));
37 // Append ")" to the end of result.
38 result.append(")");
39 // Append the result of running convert a modifier to a string given
40 // part's modifier to the end of result.
41 result.append(convert_modifier_to_string(part.modifier));
42 }
43 continue;
44 }
45
46 // Assert: part's name is not the empty string
47 ADA_ASSERT_TRUE(!part.name.empty());
48
49 // Append part's name to name list
50 name_list.push_back(part.name);
51
52 // Let regexp value be part's value
53 std::string regexp_value = part.value;
54
55 // If part's type is "segment-wildcard"
56 if (part.type == url_pattern_part_type::SEGMENT_WILDCARD) {
57 // then set regexp value to the result of running generate a segment
58 // wildcard regexp given options.
59 regexp_value = generate_segment_wildcard_regexp(options);
60 }
61 // Otherwise if part's type is "full-wildcard"
62 else if (part.type == url_pattern_part_type::FULL_WILDCARD) {
63 // then set regexp value to full wildcard regexp value.
64 regexp_value = ".*";
65 }
66
67 // If part's prefix is the empty string and part's suffix is the empty
68 // string
69 if (part.prefix.empty() && part.suffix.empty()) {
70 // If part's modifier is "none" or "optional"
71 if (part.modifier == url_pattern_part_modifier::none ||
72 part.modifier == url_pattern_part_modifier::optional) {
73 // (<regexp value>)<modifier>
74 result += "(" + regexp_value + ")" +
75 convert_modifier_to_string(part.modifier);
76 } else {
77 // ((?:<regexp value>)<modifier>)
78 result += "((?:" + regexp_value + ")" +
79 convert_modifier_to_string(part.modifier) + ")";
80 }
81 continue;
82 }
83
84 // If part's modifier is "none" or "optional"
85 if (part.modifier == url_pattern_part_modifier::none ||
86 part.modifier == url_pattern_part_modifier::optional) {
87 // (?:<prefix>(<regexp value>)<suffix>)<modifier>
88 result += "(?:" + escape_regexp_string(part.prefix) + "(" + regexp_value +
89 ")" + escape_regexp_string(part.suffix) + ")" +
90 convert_modifier_to_string(part.modifier);
91 continue;
92 }
93
94 // Assert: part's modifier is "zero-or-more" or "one-or-more"
95 ADA_ASSERT_TRUE(part.modifier == url_pattern_part_modifier::zero_or_more ||
96 part.modifier == url_pattern_part_modifier::one_or_more);
97
98 // Assert: part's prefix is not the empty string or part's suffix is not the
99 // empty string
100 ADA_ASSERT_TRUE(!part.prefix.empty() || !part.suffix.empty());
101
102 // (?:<prefix>((?:<regexp value>)(?:<suffix><prefix>(?:<regexp
103 // value>))*)<suffix>)?
104 // Append "(?:" to the end of result.
105 result.append("(?:");
106 // Append the result of running escape a regexp string given part's prefix
107 // to the end of result.
108 result.append(escape_regexp_string(part.prefix));
109 // Append "((?:" to the end of result.
110 result.append("((?:");
111 // Append regexp value to the end of result.
112 result.append(regexp_value);
113 // Append ")(?:" to the end of result.
114 result.append(")(?:");
115 // Append the result of running escape a regexp string given part's suffix
116 // to the end of result.
117 result.append(escape_regexp_string(part.suffix));
118 // Append the result of running escape a regexp string given part's prefix
119 // to the end of result.
120 result.append(escape_regexp_string(part.prefix));
121 // Append "(?:" to the end of result.
122 result.append("(?:");
123 // Append regexp value to the end of result.
124 result.append(regexp_value);
125 // Append "))*)" to the end of result.
126 result.append("))*)");
127 // Append the result of running escape a regexp string given part's suffix
128 // to the end of result.
129 result.append(escape_regexp_string(part.suffix));
130 // Append ")" to the end of result.
131 result.append(")");
132
133 // If part's modifier is "zero-or-more" then append "?" to the end of result
134 if (part.modifier == url_pattern_part_modifier::zero_or_more) {
135 result += "?";
136 }
137 }
138
139 // Append "$" to the end of result
140 result += "$";
141
142 // Return (result, name list)
143 return {std::move(result), std::move(name_list)};
144}
145
146bool is_ipv6_address(std::string_view input) noexcept {
147 // If input's code point length is less than 2, then return false.
148 if (input.size() < 2) return false;
149
150 // Let input code points be input interpreted as a list of code points.
151 // If input code points[0] is U+005B ([), then return true.
152 if (input.front() == '[') return true;
153 // If input code points[0] is U+007B ({) and input code points[1] is U+005B
154 // ([), then return true.
155 if (input.starts_with("{[")) return true;
156 // If input code points[0] is U+005C (\‍) and input code points[1] is U+005B
157 // ([), then return true.
158 return input.starts_with("\\[");
159}
160
161std::string convert_modifier_to_string(url_pattern_part_modifier modifier) {
162 // TODO: Optimize this.
163 switch (modifier) {
164 // If modifier is "zero-or-more", then return "*".
165 case url_pattern_part_modifier::zero_or_more:
166 return "*";
167 // If modifier is "optional", then return "?".
168 case url_pattern_part_modifier::optional:
169 return "?";
170 // If modifier is "one-or-more", then return "+".
171 case url_pattern_part_modifier::one_or_more:
172 return "+";
173 // Return the empty string.
174 default:
175 return "";
176 }
177}
178
179std::string generate_segment_wildcard_regexp(
180 url_pattern_compile_component_options options) {
181 // Let result be "[^".
182 std::string result = "[^";
183 // Append the result of running escape a regexp string given options's
184 // delimiter code point to the end of result.
185 result.append(escape_regexp_string(options.get_delimiter()));
186 // Append "]+?" to the end of result.
187 result.append("]+?");
188 // Return result.
189 ada_log("generate_segment_wildcard_regexp result: ", result);
190 return result;
191}
192
193tl::expected<std::string, errors> canonicalize_protocol(
194 std::string_view input) {
195 ada_log("canonicalize_protocol called with input=", input);
196 // If value is the empty string, return value.
197 if (input.empty()) [[unlikely]] {
198 return "";
199 }
200
201 // IMPORTANT: Deviation from the spec. We remove the trailing ':' here.
202 if (input.ends_with(":")) {
203 input.remove_suffix(1);
204 }
205
206 // Let dummyURL be a new URL record.
207 // Let parseResult be the result of running the basic URL parser given value
208 // followed by "://dummy.test", with dummyURL as url.
209 if (auto dummy_url = ada::parse<url_aggregator>(
210 std::string(input) + "://dummy.test", nullptr)) {
211 // IMPORTANT: Deviation from the spec. We remove the trailing ':' here.
212 // Since URL parser always return protocols ending with `:`
213 auto protocol = dummy_url->get_protocol();
214 protocol.remove_suffix(1);
215 return std::string(protocol);
216 }
217 // If parseResult is failure, then throw a TypeError.
218 return tl::unexpected(errors::type_error);
219}
220
221tl::expected<std::string, errors> canonicalize_username(
222 std::string_view input) {
223 // If value is the empty string, return value.
224 if (input.empty()) [[unlikely]] {
225 return "";
226 }
227 // Let dummyURL be a new URL record.
228 auto url = ada::parse<url_aggregator>("fake://dummy.test", nullptr);
229 ADA_ASSERT_TRUE(url.has_value());
230 // Set the username given dummyURL and value.
231 if (!url->set_username(input)) {
232 return tl::unexpected(errors::type_error);
233 }
234 // Return dummyURL's username.
235 return std::string(url->get_username());
236}
237
238tl::expected<std::string, errors> canonicalize_password(
239 std::string_view input) {
240 // If value is the empty string, return value.
241 if (input.empty()) [[unlikely]] {
242 return "";
243 }
244 // Let dummyURL be a new URL record.
245 // Set the password given dummyURL and value.
246 auto url = ada::parse<url_aggregator>("fake://dummy.test", nullptr);
247
248 ADA_ASSERT_TRUE(url.has_value());
249 if (!url->set_password(input)) {
250 return tl::unexpected(errors::type_error);
251 }
252 // Return dummyURL's password.
253 return std::string(url->get_password());
254}
255
256tl::expected<std::string, errors> canonicalize_hostname(
257 std::string_view input) {
258 ada_log("canonicalize_hostname input=", input);
259 // If value is the empty string, return value.
260 if (input.empty()) [[unlikely]] {
261 return "";
262 }
263 // Let dummyURL be a new URL record.
264 // Let parseResult be the result of running the basic URL parser given value
265 // with dummyURL as url and hostname state as state override.
266
267 // IMPORTANT: The protocol needs to be a special protocol, otherwise the
268 // hostname will not be converted using IDNA.
269 auto url = ada::parse<url_aggregator>("https://dummy.test", nullptr);
270 ADA_ASSERT_TRUE(url);
271 // if (!isValidHostnameInput(hostname)) return kj::none;
272 if (!url->set_hostname(input)) {
273 // If parseResult is failure, then throw a TypeError.
274 return tl::unexpected(errors::type_error);
275 }
276 // Return dummyURL's host, serialized, or empty string if it is null.
277 return std::string(url->get_hostname());
278}
279
280tl::expected<std::string, errors> canonicalize_ipv6_hostname(
281 std::string_view input) {
282 ada_log("canonicalize_ipv6_hostname input=", input);
283 // TODO: Optimization opportunity: Use lookup table to speed up checking
284 if (std::ranges::any_of(input, [](char c) {
285 return c != '[' && c != ']' && c != ':' &&
286 !unicode::is_ascii_hex_digit(c);
287 })) {
288 return tl::unexpected(errors::type_error);
289 }
290 // Append the result of running ASCII lowercase given code point to the end of
291 // result.
292 auto hostname = std::string(input);
293 unicode::to_lower_ascii(hostname.data(), hostname.size());
294 return hostname;
295}
296
297tl::expected<std::string, errors> canonicalize_port(
298 std::string_view port_value) {
299 // If portValue is the empty string, return portValue.
300 if (port_value.empty()) [[unlikely]] {
301 return "";
302 }
303 // Let dummyURL be a new URL record.
304 // If protocolValue was given, then set dummyURL's scheme to protocolValue.
305 // Let parseResult be the result of running basic URL parser given portValue
306 // with dummyURL as url and port state as state override.
307 auto url = ada::parse<url_aggregator>("fake://dummy.test", nullptr);
308 ADA_ASSERT_TRUE(url);
309 if (url->set_port(port_value)) {
310 // Return dummyURL's port, serialized, or empty string if it is null.
311 return std::string(url->get_port());
312 }
313 // If parseResult is failure, then throw a TypeError.
314 return tl::unexpected(errors::type_error);
315}
316
317tl::expected<std::string, errors> canonicalize_port_with_protocol(
318 std::string_view port_value, std::string_view protocol) {
319 // If portValue is the empty string, return portValue.
320 if (port_value.empty()) [[unlikely]] {
321 return "";
322 }
323
324 // TODO: Remove this
325 // We have an empty protocol because get_protocol() returns an empty string
326 // We should handle this in the caller rather than here.
327 if (protocol.empty()) {
328 protocol = "fake";
329 } else if (protocol.ends_with(":")) {
330 protocol.remove_suffix(1);
331 }
332 // Let dummyURL be a new URL record.
333 // If protocolValue was given, then set dummyURL's scheme to protocolValue.
334 // Let parseResult be the result of running basic URL parser given portValue
335 // with dummyURL as url and port state as state override.
336 auto url = ada::parse<url_aggregator>(std::string(protocol) + "://dummy.test",
337 nullptr);
338 // TODO: Remove has_port() check.
339 // This is actually a bug with url parser where set_port() returns true for
340 // "invalid80" port value.
341 if (url && url->set_port(port_value) && url->has_port()) {
342 // Return dummyURL's port, serialized, or empty string if it is null.
343 return std::string(url->get_port());
344 }
345 // TODO: Remove this once the previous has_port() check is removed.
346 if (url) {
347 if (scheme::is_special(protocol) && url->get_port().empty()) {
348 return "";
349 }
350 }
351 // If parseResult is failure, then throw a TypeError.
352 return tl::unexpected(errors::type_error);
353}
354
355tl::expected<std::string, errors> canonicalize_pathname(
356 std::string_view input) {
357 // If value is the empty string, then return value.
358 if (input.empty()) [[unlikely]] {
359 return "";
360 }
361 // Let leading slash be true if the first code point in value is U+002F (/)
362 // and otherwise false.
363 const bool leading_slash = input.starts_with("/");
364 // Let modified value be "/-" if leading slash is false and otherwise the
365 // empty string.
366 const auto modified_value = leading_slash ? "" : "/-";
367 const auto full_url =
368 std::string("fake://fake-url") + modified_value + std::string(input);
369 if (auto url = ada::parse<url_aggregator>(full_url, nullptr)) {
370 const auto pathname = url->get_pathname();
371 // If leading slash is false, then set result to the code point substring
372 // from 2 to the end of the string within result.
373 return leading_slash ? std::string(pathname)
374 : std::string(pathname.substr(2));
375 }
376 // If parseResult is failure, then throw a TypeError.
377 return tl::unexpected(errors::type_error);
378}
379
380tl::expected<std::string, errors> canonicalize_opaque_pathname(
381 std::string_view input) {
382 // If value is the empty string, return value.
383 if (input.empty()) [[unlikely]] {
384 return "";
385 }
386 // Let dummyURL be a new URL record.
387 // Set dummyURL's path to the empty string.
388 // Let parseResult be the result of running URL parsing given value with
389 // dummyURL as url and opaque path state as state override.
390 if (auto url =
391 ada::parse<url_aggregator>("fake:" + std::string(input), nullptr)) {
392 // Return the result of URL path serializing dummyURL.
393 return std::string(url->get_pathname());
394 }
395 // If parseResult is failure, then throw a TypeError.
396 return tl::unexpected(errors::type_error);
397}
398
399tl::expected<std::string, errors> canonicalize_search(std::string_view input) {
400 // If value is the empty string, return value.
401 if (input.empty()) [[unlikely]] {
402 return "";
403 }
404 // Let dummyURL be a new URL record.
405 // Set dummyURL's query to the empty string.
406 // Let parseResult be the result of running basic URL parser given value with
407 // dummyURL as url and query state as state override.
408 auto url = ada::parse<url_aggregator>("fake://dummy.test", nullptr);
409 ADA_ASSERT_TRUE(url.has_value());
410 url->set_search(input);
411 if (url->has_search()) {
412 const auto search = url->get_search();
413 if (!search.empty()) {
414 return std::string(search.substr(1));
415 }
416 return "";
417 }
418 return tl::unexpected(errors::type_error);
419}
420
421tl::expected<std::string, errors> canonicalize_hash(std::string_view input) {
422 // If value is the empty string, return value.
423 if (input.empty()) [[unlikely]] {
424 return "";
425 }
426 // Let dummyURL be a new URL record.
427 // Set dummyURL's fragment to the empty string.
428 // Let parseResult be the result of running basic URL parser given value with
429 // dummyURL as url and fragment state as state override.
430 auto url = ada::parse<url_aggregator>("fake://dummy.test", nullptr);
431 ADA_ASSERT_TRUE(url.has_value());
432 url->set_hash(input);
433 // Return dummyURL's fragment.
434 if (url->has_hash()) {
435 const auto hash = url->get_hash();
436 if (!hash.empty()) {
437 return std::string(hash.substr(1));
438 }
439 return "";
440 }
441 return tl::unexpected(errors::type_error);
442}
443
444tl::expected<std::vector<token>, errors> tokenize(std::string_view input,
445 token_policy policy) {
446 ada_log("tokenize input: ", input);
447 // Let tokenizer be a new tokenizer.
448 // Set tokenizer's input to input.
449 // Set tokenizer's policy to policy.
450 auto tokenizer = Tokenizer(input, policy);
451 // While tokenizer's index is less than tokenizer's input's code point length:
452 while (tokenizer.index < tokenizer.input.size()) {
453 // Run seek and get the next code point given tokenizer and tokenizer's
454 // index.
455 tokenizer.seek_and_get_next_code_point(tokenizer.index);
456
457 // If tokenizer's code point is U+002A (*):
458 if (tokenizer.code_point == '*') {
459 // Run add a token with default position and length given tokenizer and
460 // "asterisk".
461 tokenizer.add_token_with_defaults(token_type::ASTERISK);
462 ada_log("add ASTERISK token");
463 // Continue.
464 continue;
465 }
466
467 // If tokenizer's code point is U+002B (+) or U+003F (?):
468 if (tokenizer.code_point == '+' || tokenizer.code_point == '?') {
469 // Run add a token with default position and length given tokenizer and
470 // "other-modifier".
471 tokenizer.add_token_with_defaults(token_type::OTHER_MODIFIER);
472 // Continue.
473 continue;
474 }
475
476 // If tokenizer's code point is U+005C (\‍):
477 if (tokenizer.code_point == '\\') {
478 // If tokenizer's index is equal to tokenizer's input's code point length
479 // - 1:
480 if (tokenizer.index == tokenizer.input.size() - 1) {
481 // Run process a tokenizing error given tokenizer, tokenizer's next
482 // index, and tokenizer's index.
483 if (auto error = tokenizer.process_tokenizing_error(
484 tokenizer.next_index, tokenizer.index)) {
485 ada_log("process_tokenizing_error failed");
486 return tl::unexpected(*error);
487 }
488 continue;
489 }
490
491 // Let escaped index be tokenizer's next index.
492 auto escaped_index = tokenizer.next_index;
493 // Run get the next code point given tokenizer.
494 tokenizer.get_next_code_point();
495 // Run add a token with default length given tokenizer, "escaped-char",
496 // tokenizer's next index, and escaped index.
497 tokenizer.add_token_with_default_length(
498 token_type::ESCAPED_CHAR, tokenizer.next_index, escaped_index);
499 ada_log("add ESCAPED_CHAR token on next_index ", tokenizer.next_index,
500 " with escaped index ", escaped_index);
501 // Continue.
502 continue;
503 }
504
505 // If tokenizer's code point is U+007B ({):
506 if (tokenizer.code_point == '{') {
507 // Run add a token with default position and length given tokenizer and
508 // "open".
509 tokenizer.add_token_with_defaults(token_type::OPEN);
510 ada_log("add OPEN token");
511 continue;
512 }
513
514 // If tokenizer's code point is U+007D (}):
515 if (tokenizer.code_point == '}') {
516 // Run add a token with default position and length given tokenizer and
517 // "close".
518 tokenizer.add_token_with_defaults(token_type::CLOSE);
519 ada_log("add CLOSE token");
520 continue;
521 }
522
523 // If tokenizer's code point is U+003A (:):
524 if (tokenizer.code_point == ':') {
525 // Let name position be tokenizer's next index.
526 auto name_position = tokenizer.next_index;
527 // Let name start be name position.
528 auto name_start = name_position;
529 // While name position is less than tokenizer's input's code point length:
530 while (name_position < tokenizer.input.size()) {
531 // Run seek and get the next code point given tokenizer and name
532 // position.
533 tokenizer.seek_and_get_next_code_point(name_position);
534 // Let first code point be true if name position equals name start and
535 // false otherwise.
536 bool first_code_point = name_position == name_start;
537 // Let valid code point be the result of running is a valid name code
538 // point given tokenizer's code point and first code point.
539 auto valid_code_point =
540 idna::valid_name_code_point(tokenizer.code_point, first_code_point);
541 ada_log("tokenizer.code_point=", uint32_t(tokenizer.code_point),
542 " first_code_point=", first_code_point,
543 " valid_code_point=", valid_code_point);
544 // If valid code point is false break.
545 if (!valid_code_point) break;
546 // Set name position to tokenizer's next index.
547 name_position = tokenizer.next_index;
548 }
549
550 // If name position is less than or equal to name start:
551 if (name_position <= name_start) {
552 // Run process a tokenizing error given tokenizer, name start, and
553 // tokenizer's index.
554 if (auto error = tokenizer.process_tokenizing_error(name_start,
555 tokenizer.index)) {
556 ada_log("process_tokenizing_error failed");
557 return tl::unexpected(*error);
558 }
559 // Continue
560 continue;
561 }
562
563 // Run add a token with default length given tokenizer, "name", name
564 // position, and name start.
565 tokenizer.add_token_with_default_length(token_type::NAME, name_position,
566 name_start);
567 continue;
568 }
569
570 // If tokenizer's code point is U+0028 (():
571 if (tokenizer.code_point == '(') {
572 // Let depth be 1.
573 size_t depth = 1;
574 // Let regexp position be tokenizer's next index.
575 auto regexp_position = tokenizer.next_index;
576 // Let regexp start be regexp position.
577 auto regexp_start = regexp_position;
578 // Let error be false.
579 bool error = false;
580
581 // While regexp position is less than tokenizer's input's code point
582 // length:
583 while (regexp_position < tokenizer.input.size()) {
584 // Run seek and get the next code point given tokenizer and regexp
585 // position.
586 tokenizer.seek_and_get_next_code_point(regexp_position);
587
588 // TODO: Optimization opportunity: The next 2 if statements can be
589 // merged. If the result of running is ASCII given tokenizer's code
590 // point is false:
591 if (!unicode::is_ascii(tokenizer.code_point)) {
592 // Run process a tokenizing error given tokenizer, regexp start, and
593 // tokenizer's index.
594 if (auto process_error = tokenizer.process_tokenizing_error(
595 regexp_start, tokenizer.index)) {
596 return tl::unexpected(*process_error);
597 }
598 // Set error to true.
599 error = true;
600 break;
601 }
602
603 // If regexp position equals regexp start and tokenizer's code point is
604 // U+003F (?):
605 if (regexp_position == regexp_start && tokenizer.code_point == '?') {
606 // Run process a tokenizing error given tokenizer, regexp start, and
607 // tokenizer's index.
608 if (auto process_error = tokenizer.process_tokenizing_error(
609 regexp_start, tokenizer.index)) {
610 return tl::unexpected(*process_error);
611 }
612 // Set error to true;
613 error = true;
614 break;
615 }
616
617 // If tokenizer's code point is U+005C (\‍):
618 if (tokenizer.code_point == '\\') {
619 // If regexp position equals tokenizer's input's code point length - 1
620 if (regexp_position == tokenizer.input.size() - 1) {
621 // Run process a tokenizing error given tokenizer, regexp start, and
622 // tokenizer's index.
623 if (auto process_error = tokenizer.process_tokenizing_error(
624 regexp_start, tokenizer.index)) {
625 return tl::unexpected(*process_error);
626 }
627 // Set error to true.
628 error = true;
629 break;
630 }
631 // Run get the next code point given tokenizer.
632 tokenizer.get_next_code_point();
633 // If the result of running is ASCII given tokenizer's code point is
634 // false:
635 if (!unicode::is_ascii(tokenizer.code_point)) {
636 // Run process a tokenizing error given tokenizer, regexp start, and
637 // tokenizer's index.
638 if (auto process_error = tokenizer.process_tokenizing_error(
639 regexp_start, tokenizer.index);
640 process_error.has_value()) {
641 return tl::unexpected(*process_error);
642 }
643 // Set error to true.
644 error = true;
645 break;
646 }
647 // Set regexp position to tokenizer's next index.
648 regexp_position = tokenizer.next_index;
649 continue;
650 }
651
652 // If tokenizer's code point is U+0029 ()):
653 if (tokenizer.code_point == ')') {
654 // Decrement depth by 1.
655 depth--;
656 // If depth is 0:
657 if (depth == 0) {
658 // Set regexp position to tokenizer's next index.
659 regexp_position = tokenizer.next_index;
660 // Break.
661 break;
662 }
663 } else if (tokenizer.code_point == '(') {
664 // Otherwise if tokenizer's code point is U+0028 (():
665 // Increment depth by 1.
666 depth++;
667 // If regexp position equals tokenizer's input's code point length -
668 // 1:
669 if (regexp_position == tokenizer.input.size() - 1) {
670 // Run process a tokenizing error given tokenizer, regexp start, and
671 // tokenizer's index.
672 if (auto process_error = tokenizer.process_tokenizing_error(
673 regexp_start, tokenizer.index)) {
674 return tl::unexpected(*process_error);
675 }
676 // Set error to true.
677 error = true;
678 break;
679 }
680 // Let temporary position be tokenizer's next index.
681 auto temporary_position = tokenizer.next_index;
682 // Run get the next code point given tokenizer.
683 tokenizer.get_next_code_point();
684 // If tokenizer's code point is not U+003F (?):
685 if (tokenizer.code_point != '?') {
686 // Run process a tokenizing error given tokenizer, regexp start, and
687 // tokenizer's index.
688 if (auto process_error = tokenizer.process_tokenizing_error(
689 regexp_start, tokenizer.index)) {
690 return tl::unexpected(*process_error);
691 }
692 // Set error to true.
693 error = true;
694 break;
695 }
696 // Set tokenizer's next index to temporary position.
697 tokenizer.next_index = temporary_position;
698 }
699 // Set regexp position to tokenizer's next index.
700 regexp_position = tokenizer.next_index;
701 }
702
703 // If error is true continue.
704 if (error) continue;
705 // If depth is not zero:
706 if (depth != 0) {
707 // Run process a tokenizing error given tokenizer, regexp start, and
708 // tokenizer's index.
709 if (auto process_error = tokenizer.process_tokenizing_error(
710 regexp_start, tokenizer.index)) {
711 return tl::unexpected(*process_error);
712 }
713 continue;
714 }
715 // Let regexp length be regexp position - regexp start - 1.
716 auto regexp_length = regexp_position - regexp_start - 1;
717 // If regexp length is zero:
718 if (regexp_length == 0) {
719 // Run process a tokenizing error given tokenizer, regexp start, and
720 // tokenizer's index.
721 if (auto process_error = tokenizer.process_tokenizing_error(
722 regexp_start, tokenizer.index)) {
723 ada_log("process_tokenizing_error failed");
724 return tl::unexpected(*process_error);
725 }
726 continue;
727 }
728 // Run add a token given tokenizer, "regexp", regexp position, regexp
729 // start, and regexp length.
730 tokenizer.add_token(token_type::REGEXP, regexp_position, regexp_start,
731 regexp_length);
732 continue;
733 }
734 // Run add a token with default position and length given tokenizer and
735 // "char".
736 tokenizer.add_token_with_defaults(token_type::CHAR);
737 }
738 // Run add a token with default length given tokenizer, "end", tokenizer's
739 // index, and tokenizer's index.
740 tokenizer.add_token_with_default_length(token_type::END, tokenizer.index,
741 tokenizer.index);
742
743 ada_log("tokenizer.token_list size is: ", tokenizer.token_list.size());
744 // Return tokenizer's token list.
745 return tokenizer.token_list;
746}
747
748std::string escape_pattern_string(std::string_view input) {
749 ada_log("escape_pattern_string called with input=", input);
750 if (input.empty()) [[unlikely]] {
751 return "";
752 }
753 // Assert: input is an ASCII string.
755 // Let result be the empty string.
756 std::string result{};
757 result.reserve(input.size());
758
759 // TODO: Optimization opportunity: Use a lookup table
760 constexpr auto should_escape = [](const char c) {
761 return c == '+' || c == '*' || c == '?' || c == ':' || c == '{' ||
762 c == '}' || c == '(' || c == ')' || c == '\\';
763 };
764
765 // While index is less than input's length:
766 for (const auto& c : input) {
767 if (should_escape(c)) {
768 // then append U+005C (\‍) to the end of result.
769 result.append("\\");
770 }
771
772 // Append c to the end of result.
773 result += c;
774 }
775 // Return result.
776 return result;
777}
778
779namespace {
780constexpr std::array<uint8_t, 256> escape_regexp_table = []() consteval {
781 std::array<uint8_t, 256> out{};
782 for (auto& c : {'.', '+', '*', '?', '^', '$', '{', '}', '(', ')', '[', ']',
783 '|', '/', '\\'}) {
784 out[c] = 1;
785 }
786 return out;
787}();
788
789constexpr bool should_escape_regexp_char(char c) {
790 return escape_regexp_table[(uint8_t)c];
791}
792} // namespace
793
794std::string escape_regexp_string(std::string_view input) {
795 // Assert: input is an ASCII string.
796 ADA_ASSERT_TRUE(idna::is_ascii(input));
797 // Let result be the empty string.
798 std::string result{};
799 result.reserve(input.size());
800 for (const auto& c : input) {
801 // TODO: Optimize this even further
802 if (should_escape_regexp_char(c)) {
803 result.append(std::string("\\") + c);
804 } else {
805 result.push_back(c);
806 }
807 }
808 return result;
809}
810
811std::string process_base_url_string(std::string_view input,
812 url_pattern_init::process_type type) {
813 // If type is not "pattern" return input.
814 if (type != url_pattern_init::process_type::pattern) {
815 return std::string(input);
816 }
817 // Return the result of escaping a pattern string given input.
818 return escape_pattern_string(input);
819}
820
821constexpr bool is_absolute_pathname(
822 std::string_view input, url_pattern_init::process_type type) noexcept {
823 // If input is the empty string, then return false.
824 if (input.empty()) [[unlikely]] {
825 return false;
826 }
827 // If input[0] is U+002F (/), then return true.
828 if (input.starts_with("/")) return true;
829 // If type is "url", then return false.
830 if (type == url_pattern_init::process_type::url) return false;
831 // If input's code point length is less than 2, then return false.
832 if (input.size() < 2) return false;
833 // If input[0] is U+005C (\‍) and input[1] is U+002F (/), then return true.
834 // If input[0] is U+007B ({) and input[1] is U+002F (/), then return true.
835 // Return false.
836 return input[1] == '/' && (input[0] == '\\' || input[0] == '{');
837}
838
839std::string generate_pattern_string(
840 std::vector<url_pattern_part>& part_list,
841 url_pattern_compile_component_options& options) {
842 // Let result be the empty string.
843 std::string result{};
844 // Let index list be the result of getting the indices for part list.
845 // For each index of index list:
846 for (size_t index = 0; index < part_list.size(); index++) {
847 // Let part be part list[index].
848 auto part = part_list[index];
849 // Let previous part be part list[index - 1] if index is greater than 0,
850 // otherwise let it be null.
851 // TODO: Optimization opportunity. Find a way to avoid making a copy here.
852 std::optional<url_pattern_part> previous_part =
853 index == 0 ? std::nullopt : std::optional(part_list[index - 1]);
854 // Let next part be part list[index + 1] if index is less than index list's
855 // size - 1, otherwise let it be null.
856 std::optional<url_pattern_part> next_part =
857 index < part_list.size() - 1 ? std::optional(part_list[index + 1])
858 : std::nullopt;
859 // If part's type is "fixed-text" then:
860 if (part.type == url_pattern_part_type::FIXED_TEXT) {
861 // If part's modifier is "none" then:
862 if (part.modifier == url_pattern_part_modifier::none) {
863 // Append the result of running escape a pattern string given part's
864 // value to the end of result.
865 result.append(escape_pattern_string(part.value));
866 continue;
867 }
868 // Append "{" to the end of result.
869 result += "{";
870 // Append the result of running escape a pattern string given part's value
871 // to the end of result.
872 result.append(escape_pattern_string(part.value));
873 // Append "}" to the end of result.
874 result += "}";
875 // Append the result of running convert a modifier to a string given
876 // part's modifier to the end of result.
877 result.append(convert_modifier_to_string(part.modifier));
878 continue;
879 }
880 // Let custom name be true if part's name[0] is not an ASCII digit;
881 // otherwise false.
882 bool custom_name = !unicode::is_ascii_digit(part.name[0]);
883 // Let needs grouping be true if at least one of the following are true,
884 // otherwise let it be false:
885 // - part's suffix is not the empty string.
886 // - part's prefix is not the empty string and is not options's prefix code
887 // point.
888 bool needs_grouping =
889 !part.suffix.empty() ||
890 (!part.prefix.empty() && part.prefix[0] != options.get_prefix()[0]);
891
892 // If all of the following are true:
893 // - needs grouping is false; and
894 // - custom name is true; and
895 // - part's type is "segment-wildcard"; and
896 // - part's modifier is "none"; and
897 // - next part is not null; and
898 // - next part's prefix is the empty string; and
899 // - next part's suffix is the empty string
900 if (!needs_grouping && custom_name &&
901 part.type == url_pattern_part_type::SEGMENT_WILDCARD &&
902 part.modifier == url_pattern_part_modifier::none &&
903 next_part.has_value() && next_part->prefix.empty() &&
904 next_part->suffix.empty()) {
905 // If next part's type is "fixed-text":
906 if (next_part->type == url_pattern_part_type::FIXED_TEXT) {
907 // Set needs grouping to true if the result of running is a valid name
908 // code point given next part's value's first code point and the boolean
909 // false is true.
910 if (idna::valid_name_code_point(next_part->value[0], false)) {
911 needs_grouping = true;
912 }
913 } else {
914 // Set needs grouping to true if next part's name[0] is an ASCII digit.
915 needs_grouping = !next_part->name.empty() &&
916 unicode::is_ascii_digit(next_part->name[0]);
917 }
918 }
919
920 // If all of the following are true:
921 // - needs grouping is false; and
922 // - part's prefix is the empty string; and
923 // - previous part is not null; and
924 // - previous part's type is "fixed-text"; and
925 // - previous part's value's last code point is options's prefix code point.
926 // then set needs grouping to true.
927 if (!needs_grouping && part.prefix.empty() && previous_part.has_value() &&
928 previous_part->type == url_pattern_part_type::FIXED_TEXT &&
929 !options.get_prefix().empty() &&
930 previous_part->value.at(previous_part->value.size() - 1) ==
931 options.get_prefix()[0]) {
932 needs_grouping = true;
933 }
934
935 // Assert: part's name is not the empty string or null.
936 ADA_ASSERT_TRUE(!part.name.empty());
937
938 // If needs grouping is true, then append "{" to the end of result.
939 if (needs_grouping) {
940 result.append("{");
941 }
942
943 // Append the result of running escape a pattern string given part's prefix
944 // to the end of result.
945 result.append(escape_pattern_string(part.prefix));
946
947 // If custom name is true:
948 if (custom_name) {
949 // Append ":" to the end of result.
950 result.append(":");
951 // Append part's name to the end of result.
952 result.append(part.name);
953 }
954
955 // If part's type is "regexp" then:
956 if (part.type == url_pattern_part_type::REGEXP) {
957 // Append "(" to the end of result.
958 result.append("(");
959 // Append part's value to the end of result.
960 result.append(part.value);
961 // Append ")" to the end of result.
962 result.append(")");
963 } else if (part.type == url_pattern_part_type::SEGMENT_WILDCARD &&
964 !custom_name) {
965 // Otherwise if part's type is "segment-wildcard" and custom name is
966 // false: Append "(" to the end of result.
967 result.append("(");
968 // Append the result of running generate a segment wildcard regexp given
969 // options to the end of result.
970 result.append(generate_segment_wildcard_regexp(options));
971 // Append ")" to the end of result.
972 result.append(")");
973 } else if (part.type == url_pattern_part_type::FULL_WILDCARD) {
974 // Otherwise if part's type is "full-wildcard":
975 // If custom name is false and one of the following is true:
976 // - previous part is null; or
977 // - previous part's type is "fixed-text"; or
978 // - previous part's modifier is not "none"; or
979 // - needs grouping is true; or
980 // - part's prefix is not the empty string
981 // - then append "*" to the end of result.
982 if (!custom_name &&
983 (!previous_part.has_value() ||
984 previous_part->type == url_pattern_part_type::FIXED_TEXT ||
985 previous_part->modifier != url_pattern_part_modifier::none ||
986 needs_grouping || !part.prefix.empty())) {
987 result.append("*");
988 } else {
989 // Append "(" to the end of result.
990 // Append full wildcard regexp value to the end of result.
991 // Append ")" to the end of result.
992 result.append("(.*)");
993 }
994 }
995
996 // If all of the following are true:
997 // - part's type is "segment-wildcard"; and
998 // - custom name is true; and
999 // - part's suffix is not the empty string; and
1000 // - The result of running is a valid name code point given part's suffix's
1001 // first code point and the boolean false is true then append U+005C (\‍) to
1002 // the end of result.
1003 if (part.type == url_pattern_part_type::SEGMENT_WILDCARD && custom_name &&
1004 !part.suffix.empty() &&
1005 idna::valid_name_code_point(part.suffix[0], false)) {
1006 result.append("\\");
1007 }
1008
1009 // Append the result of running escape a pattern string given part's suffix
1010 // to the end of result.
1011 result.append(escape_pattern_string(part.suffix));
1012 // If needs grouping is true, then append "}" to the end of result.
1013 if (needs_grouping) result.append("}");
1014 // Append the result of running convert a modifier to a string given part's
1015 // modifier to the end of result.
1016 result.append(convert_modifier_to_string(part.modifier));
1017 }
1018 // Return result.
1019 return result;
1020}
1021} // namespace ada::url_pattern_helpers
1022
1023#endif // ADA_INCLUDE_URL_PATTERN
#define ADA_ASSERT_TRUE(COND)
bool constexpr is_ascii(std::u32string_view view)
errors
Definition errors.h:10
template ada::result< url_aggregator > parse< url_aggregator >(std::string_view input, const url_aggregator *base_url)
tl::expected< result_type, ada::errors > result
Declaration for the URLPattern helpers.