Ada 3.4.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 <array>
6#include <charconv>
7#include <optional>
8#include <ranges>
9#include <string>
10
11#include "ada/character_sets.h"
12#include "ada/helpers.h"
13#include "ada/scheme.h"
14#include "ada/unicode.h"
15
16namespace ada::url_pattern_helpers {
17
18std::tuple<std::string, std::vector<std::string>>
19generate_regular_expression_and_name_list(
20 const std::vector<url_pattern_part>& part_list,
21 url_pattern_compile_component_options options) {
22 // Let result be "^"
23 std::string result = "^";
24 // Reserve capacity to reduce reallocations
25 result.reserve(part_list.size() * 16);
26
27 // Let name list be a new list
28 std::vector<std::string> name_list{};
29 name_list.reserve(part_list.size());
30
31 // Pre-generate segment wildcard regexp if needed (avoids repeated generation)
32 std::string segment_wildcard_regexp;
33
34 // For each part of part list:
35 for (const url_pattern_part& part : part_list) {
36 // If part's type is "fixed-text":
37 if (part.type == url_pattern_part_type::FIXED_TEXT) {
38 // If part's modifier is "none"
39 if (part.modifier == url_pattern_part_modifier::none) {
40 result.append(escape_regexp_string(part.value));
41 } else {
42 // (?:<fixed text>)<modifier>
43 result.append("(?:");
44 result.append(escape_regexp_string(part.value));
45 result.push_back(')');
46 result.append(convert_modifier_to_string(part.modifier));
47 }
48 continue;
49 }
50
51 // Assert: part's name is not the empty string
52 ADA_ASSERT_TRUE(!part.name.empty());
53 name_list.push_back(part.name);
54
55 // Use string_view to avoid copies where possible
56 std::string_view regexp_value = part.value;
57
58 if (part.type == url_pattern_part_type::SEGMENT_WILDCARD) {
59 // Lazy generate segment wildcard regexp
60 if (segment_wildcard_regexp.empty()) {
61 segment_wildcard_regexp = generate_segment_wildcard_regexp(options);
62 }
63 regexp_value = segment_wildcard_regexp;
64 } else if (part.type == url_pattern_part_type::FULL_WILDCARD) {
65 regexp_value = ".*";
66 }
67
68 // If part's prefix is the empty string and part's suffix is the empty
69 // string
70 if (part.prefix.empty() && part.suffix.empty()) {
71 // If part's modifier is "none" or "optional"
72 if (part.modifier == url_pattern_part_modifier::none ||
73 part.modifier == url_pattern_part_modifier::optional) {
74 // (<regexp value>)<modifier>
75 result.push_back('(');
76 result.append(regexp_value);
77 result.push_back(')');
78 result.append(convert_modifier_to_string(part.modifier));
79 } else {
80 // ((?:<regexp value>)<modifier>)
81 result.append("((?:");
82 result.append(regexp_value);
83 result.push_back(')');
84 result.append(convert_modifier_to_string(part.modifier));
85 result.push_back(')');
86 }
87 continue;
88 }
89
90 // If part's modifier is "none" or "optional"
91 if (part.modifier == url_pattern_part_modifier::none ||
92 part.modifier == url_pattern_part_modifier::optional) {
93 // (?:<prefix>(<regexp value>)<suffix>)<modifier>
94 result.append("(?:");
95 result.append(escape_regexp_string(part.prefix));
96 result.push_back('(');
97 result.append(regexp_value);
98 result.push_back(')');
99 result.append(escape_regexp_string(part.suffix));
100 result.push_back(')');
101 result.append(convert_modifier_to_string(part.modifier));
102 continue;
103 }
104
105 // Assert: part's modifier is "zero-or-more" or "one-or-more"
106 ADA_ASSERT_TRUE(part.modifier == url_pattern_part_modifier::zero_or_more ||
107 part.modifier == url_pattern_part_modifier::one_or_more);
108
109 // Assert: part's prefix is not the empty string or part's suffix is not the
110 // empty string
111 ADA_ASSERT_TRUE(!part.prefix.empty() || !part.suffix.empty());
112
113 // (?:<prefix>((?:<regexp value>)(?:<suffix><prefix>(?:<regexp
114 // value>))*)<suffix>)?
115 // Append "(?:" to the end of result.
116 result.append("(?:");
117 // Append the result of running escape a regexp string given part's prefix
118 // to the end of result.
119 result.append(escape_regexp_string(part.prefix));
120 // Append "((?:" to the end of result.
121 result.append("((?:");
122 // Append regexp value to the end of result.
123 result.append(regexp_value);
124 // Append ")(?:" to the end of result.
125 result.append(")(?:");
126 // Append the result of running escape a regexp string given part's suffix
127 // to the end of result.
128 result.append(escape_regexp_string(part.suffix));
129 // Append the result of running escape a regexp string given part's prefix
130 // to the end of result.
131 result.append(escape_regexp_string(part.prefix));
132 // Append "(?:" to the end of result.
133 result.append("(?:");
134 // Append regexp value to the end of result.
135 result.append(regexp_value);
136 // Append "))*)" to the end of result.
137 result.append("))*)");
138 // Append the result of running escape a regexp string given part's suffix
139 // to the end of result.
140 result.append(escape_regexp_string(part.suffix));
141 // Append ")" to the end of result.
142 result.append(")");
143
144 // If part's modifier is "zero-or-more" then append "?" to the end of result
145 if (part.modifier == url_pattern_part_modifier::zero_or_more) {
146 result += "?";
147 }
148 }
149
150 // Append "$" to the end of result
151 result += "$";
152
153 // Return (result, name list)
154 return {std::move(result), std::move(name_list)};
155}
156
157bool is_ipv6_address(std::string_view input) noexcept {
158 // If input's code point length is less than 2, then return false.
159 if (input.size() < 2) return false;
160
161 // Let input code points be input interpreted as a list of code points.
162 // If input code points[0] is U+005B ([), then return true.
163 if (input.front() == '[') return true;
164 // If input code points[0] is U+007B ({) and input code points[1] is U+005B
165 // ([), then return true.
166 if (input.starts_with("{[")) return true;
167 // If input code points[0] is U+005C (\‍) and input code points[1] is U+005B
168 // ([), then return true.
169 return input.starts_with("\\[");
170}
171
172std::string_view convert_modifier_to_string(
173 url_pattern_part_modifier modifier) {
174 switch (modifier) {
175 // If modifier is "zero-or-more", then return "*".
176 case url_pattern_part_modifier::zero_or_more:
177 return "*";
178 // If modifier is "optional", then return "?".
179 case url_pattern_part_modifier::optional:
180 return "?";
181 // If modifier is "one-or-more", then return "+".
182 case url_pattern_part_modifier::one_or_more:
183 return "+";
184 // Return the empty string.
185 default:
186 return "";
187 }
188}
189
190std::string generate_segment_wildcard_regexp(
191 url_pattern_compile_component_options options) {
192 // Let result be "[^".
193 std::string result = "[^";
194 // Append the result of running escape a regexp string given options's
195 // delimiter code point to the end of result.
196 result.append(escape_regexp_string(options.get_delimiter()));
197 // Append "]+?" to the end of result.
198 result.append("]+?");
199 // Return result.
200 ada_log("generate_segment_wildcard_regexp result: ", result);
201 return result;
202}
203
204namespace {
205// Unified lookup table for URL pattern character classification
206// Bit flags for different character types
207constexpr uint8_t CHAR_SCHEME = 1; // valid in scheme (a-z, A-Z, 0-9, +, -, .)
208constexpr uint8_t CHAR_UPPER = 2; // uppercase letter (needs lowercasing)
209constexpr uint8_t CHAR_SIMPLE_HOSTNAME = 4; // simple hostname (a-z, 0-9, -, .)
210constexpr uint8_t CHAR_SIMPLE_PATHNAME =
211 8; // simple pathname (a-z, A-Z, 0-9, /, -, _, ~)
212
213constexpr std::array<uint8_t, 256> char_class_table = []() consteval {
214 std::array<uint8_t, 256> table{};
215 for (int c = 'a'; c <= 'z'; c++)
216 table[c] = CHAR_SCHEME | CHAR_SIMPLE_HOSTNAME | CHAR_SIMPLE_PATHNAME;
217 for (int c = 'A'; c <= 'Z'; c++)
218 table[c] = CHAR_SCHEME | CHAR_UPPER | CHAR_SIMPLE_PATHNAME;
219 for (int c = '0'; c <= '9'; c++)
220 table[c] = CHAR_SCHEME | CHAR_SIMPLE_HOSTNAME | CHAR_SIMPLE_PATHNAME;
221 table['+'] = CHAR_SCHEME;
222 table['-'] = CHAR_SCHEME | CHAR_SIMPLE_HOSTNAME | CHAR_SIMPLE_PATHNAME;
223 table['.'] =
224 CHAR_SCHEME | CHAR_SIMPLE_HOSTNAME; // not pathname (needs normalization)
225 table['/'] = CHAR_SIMPLE_PATHNAME;
226 table['_'] = CHAR_SIMPLE_PATHNAME;
227 table['~'] = CHAR_SIMPLE_PATHNAME;
228 return table;
229}();
230} // namespace
231
232tl::expected<std::string, errors> canonicalize_protocol(
233 std::string_view input) {
234 ada_log("canonicalize_protocol called with input=", input);
235 if (input.empty()) [[unlikely]] {
236 return "";
237 }
238
239 if (input.ends_with(":")) {
240 input.remove_suffix(1);
241 }
242
243 // Fast path: special schemes are already canonical
244 if (scheme::is_special(input)) {
245 return std::string(input);
246 }
247
248 // Fast path: validate scheme chars and check for uppercase
249 // First char must be alpha (not +, -, ., or digit)
250 uint8_t first_flags = char_class_table[static_cast<uint8_t>(input[0])];
251 if (!(first_flags & CHAR_SCHEME) || input[0] == '+' || input[0] == '-' ||
252 input[0] == '.' || unicode::is_ascii_digit(input[0])) {
253 return tl::unexpected(errors::type_error);
254 }
255
256 uint8_t needs_lowercase = first_flags & CHAR_UPPER;
257 for (size_t i = 1; i < input.size(); i++) {
258 uint8_t flags = char_class_table[static_cast<uint8_t>(input[i])];
259 if (!(flags & CHAR_SCHEME)) {
260 return tl::unexpected(errors::type_error);
261 }
262 needs_lowercase |= flags & CHAR_UPPER;
263 }
264
265 if (needs_lowercase == 0) {
266 return std::string(input);
267 }
268
269 std::string result(input);
270 unicode::to_lower_ascii(result.data(), result.size());
271 return result;
272}
273
274tl::expected<std::string, errors> canonicalize_username(
275 std::string_view input) {
276 // If value is the empty string, return value.
277 if (input.empty()) [[unlikely]] {
278 return "";
279 }
280 // Percent-encode the input using the userinfo percent-encode set.
282 input, character_sets::USERINFO_PERCENT_ENCODE);
283 if (idx == input.size()) {
284 // No encoding needed, return input as-is
285 return std::string(input);
286 }
287 // Percent-encode from the first character that needs encoding
288 return ada::unicode::percent_encode(
289 input, character_sets::USERINFO_PERCENT_ENCODE, idx);
290}
291
292tl::expected<std::string, errors> canonicalize_password(
293 std::string_view input) {
294 // If value is the empty string, return value.
295 if (input.empty()) [[unlikely]] {
296 return "";
297 }
298 // Percent-encode the input using the userinfo percent-encode set.
300 input, character_sets::USERINFO_PERCENT_ENCODE);
301 if (idx == input.size()) {
302 // No encoding needed, return input as-is
303 return std::string(input);
304 }
305 // Percent-encode from the first character that needs encoding
306 return ada::unicode::percent_encode(
307 input, character_sets::USERINFO_PERCENT_ENCODE, idx);
308}
309
310tl::expected<std::string, errors> canonicalize_hostname(
311 std::string_view input) {
312 ada_log("canonicalize_hostname input=", input);
313 if (input.empty()) [[unlikely]] {
314 return "";
315 }
316
317 // Fast path: simple hostnames (lowercase ASCII, digits, -, .) need no IDNA
318 bool needs_processing = false;
319 for (char c : input) {
320 needs_processing |=
321 !(char_class_table[static_cast<uint8_t>(c)] & CHAR_SIMPLE_HOSTNAME);
322 }
323 if (!needs_processing) {
324 return std::string(input);
325 }
326
327 // Let dummyURL be a new URL record.
328 // Let parseResult be the result of running the basic URL parser given value
329 // with dummyURL as url and hostname state as state override.
330
331 // IMPORTANT: The protocol needs to be a special protocol, otherwise the
332 // hostname will not be converted using IDNA.
333 auto url = ada::parse<url_aggregator>("https://dummy.test", nullptr);
334 ADA_ASSERT_TRUE(url);
335 // if (!isValidHostnameInput(hostname)) return kj::none;
336 if (!url->set_hostname(input)) {
337 // If parseResult is failure, then throw a TypeError.
338 return tl::unexpected(errors::type_error);
339 }
340 // Return dummyURL's host, serialized, or empty string if it is null.
341 return std::string(url->get_hostname());
342}
343
344tl::expected<std::string, errors> canonicalize_ipv6_hostname(
345 std::string_view input) {
346 ada_log("canonicalize_ipv6_hostname input=", input);
347 // TODO: Optimization opportunity: Use lookup table to speed up checking
348 if (std::ranges::any_of(input, [](char c) {
349 return c != '[' && c != ']' && c != ':' &&
350 !unicode::is_ascii_hex_digit(c);
351 })) {
352 return tl::unexpected(errors::type_error);
353 }
354 // Append the result of running ASCII lowercase given code point to the end of
355 // result.
356 auto hostname = std::string(input);
357 unicode::to_lower_ascii(hostname.data(), hostname.size());
358 return hostname;
359}
360
361tl::expected<std::string, errors> canonicalize_port(
362 std::string_view port_value) {
363 // If portValue is the empty string, return portValue.
364 if (port_value.empty()) [[unlikely]] {
365 return "";
366 }
367
368 // Remove ASCII tab or newline characters
369 std::string trimmed(port_value);
370 helpers::remove_ascii_tab_or_newline(trimmed);
371
372 if (trimmed.empty()) {
373 return "";
374 }
375
376 // Input should start with a digit character
377 if (!unicode::is_ascii_digit(trimmed.front())) {
378 return tl::unexpected(errors::type_error);
379 }
380
381 // Find the first non-digit character
382 auto first_non_digit =
383 std::ranges::find_if_not(trimmed, unicode::is_ascii_digit);
384 std::string_view digits_to_parse =
385 std::string_view(trimmed.data(), first_non_digit - trimmed.begin());
386
387 // Here we have that a range of ASCII digit characters identified
388 // by digits_to_parse. It is none empty.
389 // We want to determine whether it is a valid port number (0-65535).
390 // Clearly, if the length is greater than 5, it is invalid.
391 // If the length is 5, we need to compare lexicographically to "65535".
392 // Otherwise it is valid.
393 if (digits_to_parse.size() == 5) {
394 if (digits_to_parse > "65535") {
395 return tl::unexpected(errors::type_error);
396 }
397 } else if (digits_to_parse.size() > 5) {
398 return tl::unexpected(errors::type_error);
399 }
400 if (digits_to_parse[0] == '0' && digits_to_parse.size() > 1) {
401 // Leading zeros are not allowed for multi-digit ports
402 return tl::unexpected(errors::type_error);
403 }
404 // It is valid! Most times, we do not need to parse it into an integer.
405 return std::string(digits_to_parse);
406}
407
408tl::expected<std::string, errors> canonicalize_port_with_protocol(
409 std::string_view port_value, std::string_view protocol) {
410 // If portValue is the empty string, return portValue.
411 if (port_value.empty()) [[unlikely]] {
412 return "";
413 }
414
415 // Handle empty or trailing colon in protocol
416 if (protocol.empty()) {
417 protocol = "fake";
418 } else if (protocol.ends_with(":")) {
419 protocol.remove_suffix(1);
420 }
421
422 // Remove ASCII tab or newline characters
423 std::string trimmed(port_value);
424 helpers::remove_ascii_tab_or_newline(trimmed);
425
426 if (trimmed.empty()) {
427 return "";
428 }
429
430 // Input should start with a digit character
431 if (!unicode::is_ascii_digit(trimmed.front())) {
432 return tl::unexpected(errors::type_error);
433 }
434
435 // Find the first non-digit character
436 auto first_non_digit =
437 std::ranges::find_if_not(trimmed, unicode::is_ascii_digit);
438 std::string_view digits_to_parse =
439 std::string_view(trimmed.data(), first_non_digit - trimmed.begin());
440
441 // Parse the port number
442 uint16_t parsed_port{};
443 auto result = std::from_chars(digits_to_parse.data(),
444 digits_to_parse.data() + digits_to_parse.size(),
445 parsed_port);
446
447 if (result.ec == std::errc::result_out_of_range) {
448 return tl::unexpected(errors::type_error);
449 }
450
451 if (result.ec == std::errc()) {
452 // Check if this is the default port for the scheme
453 uint16_t default_port = scheme::get_special_port(protocol);
454
455 // If it's the default port for a special scheme, return empty string
456 if (default_port != 0 && default_port == parsed_port) {
457 return "";
458 }
459
460 // Successfully parsed, return as string
461 return std::to_string(parsed_port);
462 }
463
464 return tl::unexpected(errors::type_error);
465}
466
467tl::expected<std::string, errors> canonicalize_pathname(
468 std::string_view input) {
469 if (input.empty()) [[unlikely]] {
470 return "";
471 }
472
473 // Fast path: simple pathnames (no . which needs normalization) can be
474 // returned as-is
475 bool needs_processing = false;
476 for (char c : input) {
477 needs_processing |=
478 !(char_class_table[static_cast<uint8_t>(c)] & CHAR_SIMPLE_PATHNAME);
479 }
480 if (!needs_processing) {
481 return std::string(input);
482 }
483
484 // Let leading slash be true if the first code point in value is U+002F (/)
485 // and otherwise false.
486 const bool leading_slash = input.starts_with("/");
487 // Let modified value be "/-" if leading slash is false and otherwise the
488 // empty string.
489 const auto modified_value = leading_slash ? "" : "/-";
490 const auto full_url =
491 std::string("fake://fake-url") + modified_value + std::string(input);
492 if (auto url = ada::parse<url_aggregator>(full_url, nullptr)) {
493 const auto pathname = url->get_pathname();
494 // If leading slash is false, then set result to the code point substring
495 // from 2 to the end of the string within result.
496 return leading_slash ? std::string(pathname)
497 : std::string(pathname.substr(2));
498 }
499 // If parseResult is failure, then throw a TypeError.
500 return tl::unexpected(errors::type_error);
501}
502
503tl::expected<std::string, errors> canonicalize_opaque_pathname(
504 std::string_view input) {
505 // If value is the empty string, return value.
506 if (input.empty()) [[unlikely]] {
507 return "";
508 }
509 // Let dummyURL be a new URL record.
510 // Set dummyURL's path to the empty string.
511 // Let parseResult be the result of running URL parsing given value with
512 // dummyURL as url and opaque path state as state override.
513 if (auto url =
514 ada::parse<url_aggregator>("fake:" + std::string(input), nullptr)) {
515 // Return the result of URL path serializing dummyURL.
516 return std::string(url->get_pathname());
517 }
518 // If parseResult is failure, then throw a TypeError.
519 return tl::unexpected(errors::type_error);
520}
521
522tl::expected<std::string, errors> canonicalize_search(std::string_view input) {
523 // If value is the empty string, return value.
524 if (input.empty()) [[unlikely]] {
525 return "";
526 }
527 // Remove leading '?' if present
528 std::string new_value;
529 new_value = input[0] == '?' ? input.substr(1) : input;
530 // Remove ASCII tab or newline characters
531 helpers::remove_ascii_tab_or_newline(new_value);
532
533 if (new_value.empty()) {
534 return "";
535 }
536
537 // Percent-encode using QUERY_PERCENT_ENCODE (for non-special URLs)
538 // Note: "fake://dummy.test" is not a special URL, so we use
539 // QUERY_PERCENT_ENCODE
541 new_value, character_sets::QUERY_PERCENT_ENCODE);
542 if (idx == new_value.size()) {
543 // No encoding needed
544 return new_value;
545 }
546 // Percent-encode from the first character that needs encoding
547 return ada::unicode::percent_encode(
548 new_value, character_sets::QUERY_PERCENT_ENCODE, idx);
549}
550
551tl::expected<std::string, errors> canonicalize_hash(std::string_view input) {
552 // If value is the empty string, return value.
553 if (input.empty()) [[unlikely]] {
554 return "";
555 }
556 // Remove leading '#' if present
557 std::string new_value;
558 new_value = input[0] == '#' ? input.substr(1) : input;
559 // Remove ASCII tab or newline characters
560 helpers::remove_ascii_tab_or_newline(new_value);
561
562 if (new_value.empty()) {
563 return "";
564 }
565
566 // Percent-encode using FRAGMENT_PERCENT_ENCODE
568 new_value, character_sets::FRAGMENT_PERCENT_ENCODE);
569 if (idx == new_value.size()) {
570 // No encoding needed
571 return new_value;
572 }
573 // Percent-encode from the first character that needs encoding
574 return ada::unicode::percent_encode(
575 new_value, character_sets::FRAGMENT_PERCENT_ENCODE, idx);
576}
577
578tl::expected<std::vector<token>, errors> tokenize(std::string_view input,
579 token_policy policy) {
580 ada_log("tokenize input: ", input);
581 // Let tokenizer be a new tokenizer.
582 // Set tokenizer's input to input.
583 // Set tokenizer's policy to policy.
584 auto tokenizer = Tokenizer(input, policy);
585 // While tokenizer's index is less than tokenizer's input's code point length:
586 while (tokenizer.index < tokenizer.input.size()) {
587 // Run seek and get the next code point given tokenizer and tokenizer's
588 // index.
589 tokenizer.seek_and_get_next_code_point(tokenizer.index);
590
591 // If tokenizer's code point is U+002A (*):
592 if (tokenizer.code_point == '*') {
593 // Run add a token with default position and length given tokenizer and
594 // "asterisk".
595 tokenizer.add_token_with_defaults(token_type::ASTERISK);
596 ada_log("add ASTERISK token");
597 // Continue.
598 continue;
599 }
600
601 // If tokenizer's code point is U+002B (+) or U+003F (?):
602 if (tokenizer.code_point == '+' || tokenizer.code_point == '?') {
603 // Run add a token with default position and length given tokenizer and
604 // "other-modifier".
605 tokenizer.add_token_with_defaults(token_type::OTHER_MODIFIER);
606 // Continue.
607 continue;
608 }
609
610 // If tokenizer's code point is U+005C (\‍):
611 if (tokenizer.code_point == '\\') {
612 // If tokenizer's index is equal to tokenizer's input's code point length
613 // - 1:
614 if (tokenizer.index == tokenizer.input.size() - 1) {
615 // Run process a tokenizing error given tokenizer, tokenizer's next
616 // index, and tokenizer's index.
617 if (auto error = tokenizer.process_tokenizing_error(
618 tokenizer.next_index, tokenizer.index)) {
619 ada_log("process_tokenizing_error failed");
620 return tl::unexpected(*error);
621 }
622 continue;
623 }
624
625 // Let escaped index be tokenizer's next index.
626 auto escaped_index = tokenizer.next_index;
627 // Run get the next code point given tokenizer.
628 tokenizer.get_next_code_point();
629 // Run add a token with default length given tokenizer, "escaped-char",
630 // tokenizer's next index, and escaped index.
631 tokenizer.add_token_with_default_length(
632 token_type::ESCAPED_CHAR, tokenizer.next_index, escaped_index);
633 ada_log("add ESCAPED_CHAR token on next_index ", tokenizer.next_index,
634 " with escaped index ", escaped_index);
635 // Continue.
636 continue;
637 }
638
639 // If tokenizer's code point is U+007B ({):
640 if (tokenizer.code_point == '{') {
641 // Run add a token with default position and length given tokenizer and
642 // "open".
643 tokenizer.add_token_with_defaults(token_type::OPEN);
644 ada_log("add OPEN token");
645 continue;
646 }
647
648 // If tokenizer's code point is U+007D (}):
649 if (tokenizer.code_point == '}') {
650 // Run add a token with default position and length given tokenizer and
651 // "close".
652 tokenizer.add_token_with_defaults(token_type::CLOSE);
653 ada_log("add CLOSE token");
654 continue;
655 }
656
657 // If tokenizer's code point is U+003A (:):
658 if (tokenizer.code_point == ':') {
659 // Let name position be tokenizer's next index.
660 auto name_position = tokenizer.next_index;
661 // Let name start be name position.
662 auto name_start = name_position;
663 // While name position is less than tokenizer's input's code point length:
664 while (name_position < tokenizer.input.size()) {
665 // Run seek and get the next code point given tokenizer and name
666 // position.
667 tokenizer.seek_and_get_next_code_point(name_position);
668 // Let first code point be true if name position equals name start and
669 // false otherwise.
670 bool first_code_point = name_position == name_start;
671 // Let valid code point be the result of running is a valid name code
672 // point given tokenizer's code point and first code point.
673 auto valid_code_point =
674 idna::valid_name_code_point(tokenizer.code_point, first_code_point);
675 ada_log("tokenizer.code_point=", uint32_t(tokenizer.code_point),
676 " first_code_point=", first_code_point,
677 " valid_code_point=", valid_code_point);
678 // If valid code point is false break.
679 if (!valid_code_point) break;
680 // Set name position to tokenizer's next index.
681 name_position = tokenizer.next_index;
682 }
683
684 // If name position is less than or equal to name start:
685 if (name_position <= name_start) {
686 // Run process a tokenizing error given tokenizer, name start, and
687 // tokenizer's index.
688 if (auto error = tokenizer.process_tokenizing_error(name_start,
689 tokenizer.index)) {
690 ada_log("process_tokenizing_error failed");
691 return tl::unexpected(*error);
692 }
693 // Continue
694 continue;
695 }
696
697 // Run add a token with default length given tokenizer, "name", name
698 // position, and name start.
699 tokenizer.add_token_with_default_length(token_type::NAME, name_position,
700 name_start);
701 continue;
702 }
703
704 // If tokenizer's code point is U+0028 (():
705 if (tokenizer.code_point == '(') {
706 // Let depth be 1.
707 size_t depth = 1;
708 // Let regexp position be tokenizer's next index.
709 auto regexp_position = tokenizer.next_index;
710 // Let regexp start be regexp position.
711 auto regexp_start = regexp_position;
712 // Let error be false.
713 bool error = false;
714
715 // While regexp position is less than tokenizer's input's code point
716 // length:
717 while (regexp_position < tokenizer.input.size()) {
718 // Run seek and get the next code point given tokenizer and regexp
719 // position.
720 tokenizer.seek_and_get_next_code_point(regexp_position);
721
722 // TODO: Optimization opportunity: The next 2 if statements can be
723 // merged. If the result of running is ASCII given tokenizer's code
724 // point is false:
725 if (!unicode::is_ascii(tokenizer.code_point)) {
726 // Run process a tokenizing error given tokenizer, regexp start, and
727 // tokenizer's index.
728 if (auto process_error = tokenizer.process_tokenizing_error(
729 regexp_start, tokenizer.index)) {
730 return tl::unexpected(*process_error);
731 }
732 // Set error to true.
733 error = true;
734 break;
735 }
736
737 // If regexp position equals regexp start and tokenizer's code point is
738 // U+003F (?):
739 if (regexp_position == regexp_start && tokenizer.code_point == '?') {
740 // Run process a tokenizing error given tokenizer, regexp start, and
741 // tokenizer's index.
742 if (auto process_error = tokenizer.process_tokenizing_error(
743 regexp_start, tokenizer.index)) {
744 return tl::unexpected(*process_error);
745 }
746 // Set error to true;
747 error = true;
748 break;
749 }
750
751 // If tokenizer's code point is U+005C (\‍):
752 if (tokenizer.code_point == '\\') {
753 // If regexp position equals tokenizer's input's code point length - 1
754 if (regexp_position == tokenizer.input.size() - 1) {
755 // Run process a tokenizing error given tokenizer, regexp start, and
756 // tokenizer's index.
757 if (auto process_error = tokenizer.process_tokenizing_error(
758 regexp_start, tokenizer.index)) {
759 return tl::unexpected(*process_error);
760 }
761 // Set error to true.
762 error = true;
763 break;
764 }
765 // Run get the next code point given tokenizer.
766 tokenizer.get_next_code_point();
767 // If the result of running is ASCII given tokenizer's code point is
768 // false:
769 if (!unicode::is_ascii(tokenizer.code_point)) {
770 // Run process a tokenizing error given tokenizer, regexp start, and
771 // tokenizer's index.
772 if (auto process_error = tokenizer.process_tokenizing_error(
773 regexp_start, tokenizer.index);
774 process_error.has_value()) {
775 return tl::unexpected(*process_error);
776 }
777 // Set error to true.
778 error = true;
779 break;
780 }
781 // Set regexp position to tokenizer's next index.
782 regexp_position = tokenizer.next_index;
783 continue;
784 }
785
786 // If tokenizer's code point is U+0029 ()):
787 if (tokenizer.code_point == ')') {
788 // Decrement depth by 1.
789 depth--;
790 // If depth is 0:
791 if (depth == 0) {
792 // Set regexp position to tokenizer's next index.
793 regexp_position = tokenizer.next_index;
794 // Break.
795 break;
796 }
797 } else if (tokenizer.code_point == '(') {
798 // Otherwise if tokenizer's code point is U+0028 (():
799 // Increment depth by 1.
800 depth++;
801 // If regexp position equals tokenizer's input's code point length -
802 // 1:
803 if (regexp_position == tokenizer.input.size() - 1) {
804 // Run process a tokenizing error given tokenizer, regexp start, and
805 // tokenizer's index.
806 if (auto process_error = tokenizer.process_tokenizing_error(
807 regexp_start, tokenizer.index)) {
808 return tl::unexpected(*process_error);
809 }
810 // Set error to true.
811 error = true;
812 break;
813 }
814 // Let temporary position be tokenizer's next index.
815 auto temporary_position = tokenizer.next_index;
816 // Run get the next code point given tokenizer.
817 tokenizer.get_next_code_point();
818 // If tokenizer's code point is not U+003F (?):
819 if (tokenizer.code_point != '?') {
820 // Run process a tokenizing error given tokenizer, regexp start, and
821 // tokenizer's index.
822 if (auto process_error = tokenizer.process_tokenizing_error(
823 regexp_start, tokenizer.index)) {
824 return tl::unexpected(*process_error);
825 }
826 // Set error to true.
827 error = true;
828 break;
829 }
830 // Set tokenizer's next index to temporary position.
831 tokenizer.next_index = temporary_position;
832 }
833 // Set regexp position to tokenizer's next index.
834 regexp_position = tokenizer.next_index;
835 }
836
837 // If error is true continue.
838 if (error) continue;
839 // If depth is not zero:
840 if (depth != 0) {
841 // Run process a tokenizing error given tokenizer, regexp start, and
842 // tokenizer's index.
843 if (auto process_error = tokenizer.process_tokenizing_error(
844 regexp_start, tokenizer.index)) {
845 return tl::unexpected(*process_error);
846 }
847 continue;
848 }
849 // Let regexp length be regexp position - regexp start - 1.
850 auto regexp_length = regexp_position - regexp_start - 1;
851 // If regexp length is zero:
852 if (regexp_length == 0) {
853 // Run process a tokenizing error given tokenizer, regexp start, and
854 // tokenizer's index.
855 if (auto process_error = tokenizer.process_tokenizing_error(
856 regexp_start, tokenizer.index)) {
857 ada_log("process_tokenizing_error failed");
858 return tl::unexpected(*process_error);
859 }
860 continue;
861 }
862 // Run add a token given tokenizer, "regexp", regexp position, regexp
863 // start, and regexp length.
864 tokenizer.add_token(token_type::REGEXP, regexp_position, regexp_start,
865 regexp_length);
866 continue;
867 }
868 // Run add a token with default position and length given tokenizer and
869 // "char".
870 tokenizer.add_token_with_defaults(token_type::CHAR);
871 }
872 // Run add a token with default length given tokenizer, "end", tokenizer's
873 // index, and tokenizer's index.
874 tokenizer.add_token_with_default_length(token_type::END, tokenizer.index,
875 tokenizer.index);
876
877 ada_log("tokenizer.token_list size is: ", tokenizer.token_list.size());
878 // Return tokenizer's token list.
879 return tokenizer.token_list;
880}
881
882namespace {
883constexpr std::array<uint8_t, 256> escape_pattern_table = []() consteval {
884 std::array<uint8_t, 256> out{};
885 for (auto& c : {'+', '*', '?', ':', '{', '}', '(', ')', '\\'}) {
886 out[c] = 1;
887 }
888 return out;
889}();
890
891constexpr bool should_escape_pattern_char(char c) {
892 return escape_pattern_table[static_cast<uint8_t>(c)];
893}
894} // namespace
895
896std::string escape_pattern_string(std::string_view input) {
897 ada_log("escape_pattern_string called with input=", input);
898 if (input.empty()) [[unlikely]] {
899 return "";
900 }
901 // Assert: input is an ASCII string.
903 // Let result be the empty string.
904 std::string result{};
905 // Reserve extra space for potential escapes
906 result.reserve(input.size() * 2);
907
908 // While index is less than input's length:
909 for (const char c : input) {
910 if (should_escape_pattern_char(c)) {
911 // Append U+005C (\‍) to the end of result.
912 result.push_back('\\');
913 }
914 // Append c to the end of result.
915 result.push_back(c);
916 }
917 // Return result.
918 return result;
919}
920
921namespace {
922constexpr std::array<uint8_t, 256> escape_regexp_table = []() consteval {
923 std::array<uint8_t, 256> out{};
924 for (auto& c : {'.', '+', '*', '?', '^', '$', '{', '}', '(', ')', '[', ']',
925 '|', '/', '\\'}) {
926 out[c] = 1;
927 }
928 return out;
929}();
930
931constexpr bool should_escape_regexp_char(char c) {
932 return escape_regexp_table[(uint8_t)c];
933}
934} // namespace
935
936std::string escape_regexp_string(std::string_view input) {
937 // Assert: input is an ASCII string.
938 ADA_ASSERT_TRUE(idna::is_ascii(input));
939 // Let result be the empty string.
940 std::string result{};
941 // Reserve extra space for potential escapes (worst case: all chars escaped)
942 result.reserve(input.size() * 2);
943 for (const char c : input) {
944 if (should_escape_regexp_char(c)) {
945 // Avoid temporary string allocation - directly append characters
946 result.push_back('\\');
947 result.push_back(c);
948 } else {
949 result.push_back(c);
950 }
951 }
952 return result;
953}
954
955std::string process_base_url_string(std::string_view input,
956 url_pattern_init::process_type type) {
957 // If type is not "pattern" return input.
958 if (type != url_pattern_init::process_type::pattern) {
959 return std::string(input);
960 }
961 // Return the result of escaping a pattern string given input.
962 return escape_pattern_string(input);
963}
964
965constexpr bool is_absolute_pathname(
966 std::string_view input, url_pattern_init::process_type type) noexcept {
967 // If input is the empty string, then return false.
968 if (input.empty()) [[unlikely]] {
969 return false;
970 }
971 // If input[0] is U+002F (/), then return true.
972 if (input.starts_with("/")) return true;
973 // If type is "url", then return false.
974 if (type == url_pattern_init::process_type::url) return false;
975 // If input's code point length is less than 2, then return false.
976 if (input.size() < 2) return false;
977 // If input[0] is U+005C (\‍) and input[1] is U+002F (/), then return true.
978 // If input[0] is U+007B ({) and input[1] is U+002F (/), then return true.
979 // Return false.
980 return input[1] == '/' && (input[0] == '\\' || input[0] == '{');
981}
982
983std::string generate_pattern_string(
984 std::vector<url_pattern_part>& part_list,
985 url_pattern_compile_component_options& options) {
986 // Let result be the empty string.
987 std::string result{};
988 // Let index list be the result of getting the indices for part list.
989 // For each index of index list:
990 for (size_t index = 0; index < part_list.size(); index++) {
991 // Let part be part list[index].
992 // Use reference to avoid copy
993 const auto& part = part_list[index];
994 // Let previous part be part list[index - 1] if index is greater than 0,
995 // otherwise let it be null.
996 // Use pointer to avoid copy
997 const url_pattern_part* previous_part =
998 index == 0 ? nullptr : &part_list[index - 1];
999 // Let next part be part list[index + 1] if index is less than index list's
1000 // size - 1, otherwise let it be null.
1001 const url_pattern_part* next_part =
1002 index < part_list.size() - 1 ? &part_list[index + 1] : nullptr;
1003 // If part's type is "fixed-text" then:
1004 if (part.type == url_pattern_part_type::FIXED_TEXT) {
1005 // If part's modifier is "none" then:
1006 if (part.modifier == url_pattern_part_modifier::none) {
1007 // Append the result of running escape a pattern string given part's
1008 // value to the end of result.
1009 result.append(escape_pattern_string(part.value));
1010 continue;
1011 }
1012 // Append "{" to the end of result.
1013 result += "{";
1014 // Append the result of running escape a pattern string given part's value
1015 // to the end of result.
1016 result.append(escape_pattern_string(part.value));
1017 // Append "}" to the end of result.
1018 result += "}";
1019 // Append the result of running convert a modifier to a string given
1020 // part's modifier to the end of result.
1021 result.append(convert_modifier_to_string(part.modifier));
1022 continue;
1023 }
1024 // Let custom name be true if part's name[0] is not an ASCII digit;
1025 // otherwise false.
1026 bool custom_name = !unicode::is_ascii_digit(part.name[0]);
1027 // Let needs grouping be true if at least one of the following are true,
1028 // otherwise let it be false:
1029 // - part's suffix is not the empty string.
1030 // - part's prefix is not the empty string and is not options's prefix code
1031 // point.
1032 bool needs_grouping =
1033 !part.suffix.empty() ||
1034 (!part.prefix.empty() && part.prefix[0] != options.get_prefix()[0]);
1035
1036 // If all of the following are true:
1037 // - needs grouping is false; and
1038 // - custom name is true; and
1039 // - part's type is "segment-wildcard"; and
1040 // - part's modifier is "none"; and
1041 // - next part is not null; and
1042 // - next part's prefix is the empty string; and
1043 // - next part's suffix is the empty string
1044 if (!needs_grouping && custom_name &&
1045 part.type == url_pattern_part_type::SEGMENT_WILDCARD &&
1046 part.modifier == url_pattern_part_modifier::none && next_part &&
1047 next_part->prefix.empty() && next_part->suffix.empty()) {
1048 // If next part's type is "fixed-text":
1049 if (next_part->type == url_pattern_part_type::FIXED_TEXT) {
1050 // Set needs grouping to true if the result of running is a valid name
1051 // code point given next part's value's first code point and the boolean
1052 // false is true.
1053 if (idna::valid_name_code_point(next_part->value[0], false)) {
1054 needs_grouping = true;
1055 }
1056 } else {
1057 // Set needs grouping to true if next part's name[0] is an ASCII digit.
1058 needs_grouping = !next_part->name.empty() &&
1059 unicode::is_ascii_digit(next_part->name[0]);
1060 }
1061 }
1062
1063 // If all of the following are true:
1064 // - needs grouping is false; and
1065 // - part's prefix is the empty string; and
1066 // - previous part is not null; and
1067 // - previous part's type is "fixed-text"; and
1068 // - previous part's value's last code point is options's prefix code point.
1069 // then set needs grouping to true.
1070 if (!needs_grouping && part.prefix.empty() && previous_part &&
1071 previous_part->type == url_pattern_part_type::FIXED_TEXT &&
1072 !options.get_prefix().empty() &&
1073 previous_part->value.at(previous_part->value.size() - 1) ==
1074 options.get_prefix()[0]) {
1075 needs_grouping = true;
1076 }
1077
1078 // Assert: part's name is not the empty string or null.
1079 ADA_ASSERT_TRUE(!part.name.empty());
1080
1081 // If needs grouping is true, then append "{" to the end of result.
1082 if (needs_grouping) {
1083 result.append("{");
1084 }
1085
1086 // Append the result of running escape a pattern string given part's prefix
1087 // to the end of result.
1088 result.append(escape_pattern_string(part.prefix));
1089
1090 // If custom name is true:
1091 if (custom_name) {
1092 // Append ":" to the end of result.
1093 result.append(":");
1094 // Append part's name to the end of result.
1095 result.append(part.name);
1096 }
1097
1098 // If part's type is "regexp" then:
1099 if (part.type == url_pattern_part_type::REGEXP) {
1100 // Append "(" to the end of result.
1101 result.append("(");
1102 // Append part's value to the end of result.
1103 result.append(part.value);
1104 // Append ")" to the end of result.
1105 result.append(")");
1106 } else if (part.type == url_pattern_part_type::SEGMENT_WILDCARD &&
1107 !custom_name) {
1108 // Otherwise if part's type is "segment-wildcard" and custom name is
1109 // false: Append "(" to the end of result.
1110 result.append("(");
1111 // Append the result of running generate a segment wildcard regexp given
1112 // options to the end of result.
1113 result.append(generate_segment_wildcard_regexp(options));
1114 // Append ")" to the end of result.
1115 result.append(")");
1116 } else if (part.type == url_pattern_part_type::FULL_WILDCARD) {
1117 // Otherwise if part's type is "full-wildcard":
1118 // If custom name is false and one of the following is true:
1119 // - previous part is null; or
1120 // - previous part's type is "fixed-text"; or
1121 // - previous part's modifier is not "none"; or
1122 // - needs grouping is true; or
1123 // - part's prefix is not the empty string
1124 // - then append "*" to the end of result.
1125 if (!custom_name &&
1126 (!previous_part ||
1127 previous_part->type == url_pattern_part_type::FIXED_TEXT ||
1128 previous_part->modifier != url_pattern_part_modifier::none ||
1129 needs_grouping || !part.prefix.empty())) {
1130 result.append("*");
1131 } else {
1132 // Append "(" to the end of result.
1133 // Append full wildcard regexp value to the end of result.
1134 // Append ")" to the end of result.
1135 result.append("(.*)");
1136 }
1137 }
1138
1139 // If all of the following are true:
1140 // - part's type is "segment-wildcard"; and
1141 // - custom name is true; and
1142 // - part's suffix is not the empty string; and
1143 // - The result of running is a valid name code point given part's suffix's
1144 // first code point and the boolean false is true then append U+005C (\‍) to
1145 // the end of result.
1146 if (part.type == url_pattern_part_type::SEGMENT_WILDCARD && custom_name &&
1147 !part.suffix.empty() &&
1148 idna::valid_name_code_point(part.suffix[0], false)) {
1149 result.append("\\");
1150 }
1151
1152 // Append the result of running escape a pattern string given part's suffix
1153 // to the end of result.
1154 result.append(escape_pattern_string(part.suffix));
1155 // If needs grouping is true, then append "}" to the end of result.
1156 if (needs_grouping) result.append("}");
1157 // Append the result of running convert a modifier to a string given part's
1158 // modifier to the end of result.
1159 result.append(convert_modifier_to_string(part.modifier));
1160 }
1161 // Return result.
1162 return result;
1163}
1164} // namespace ada::url_pattern_helpers
1165
1166#endif // ADA_INCLUDE_URL_PATTERN
Declaration of the character sets used by unicode functions.
#define ADA_ASSERT_TRUE(COND)
Definitions for helper functions used within Ada.
bool constexpr is_ascii(std::u32string_view view)
const uint32_t table[8150][2]
Definition ada_idna.cpp:590
ada_really_inline size_t percent_encode_index(const std::string_view input, const uint8_t character_set[])
Definition unicode-inl.h:19
errors
Error codes for URL parsing operations.
Definition errors.h:17
template ada::result< url_aggregator > parse< url_aggregator >(std::string_view input, const url_aggregator *base_url)
tl::expected< result_type, ada::errors > result
URL scheme type definitions and utilities.
Definitions for all unicode specific functions.
Declaration for the URLPattern helpers.