Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-foundation

Source of release 0.6.0

0.6.0 / src / web_url / pattern_string.lucb

#==============================================================================================
#
#   pattern_string - URLPattern: escaping, the segment wildcard, generating a pattern string
#
#   DESCRIPTION:
#       Port of Libraries/LibURL/Pattern/String.cpp (lines 1-310) and
#       Libraries/LibURL/Pattern/String.h (lines 1-23; full_wildcard_regexp_value is in
#       types_string.lucb). generate_a_pattern_string's ReadonlySpan<Part> is the Vector of parts
#       every caller passes.
#
#==============================================================================================

## Ported from Libraries/LibURL/Pattern/String.cpp:14 URL::Pattern::escape_a_pattern_string.
# https://urlpattern.spec.whatwg.org/#escape-a-pattern-string
pub func pattern_escape_a_pattern_string(input: ak.String) -> ak.String:
    # 1. Assert: input is an ASCII string.
    assert(ak.string_is_ascii(&input))

    # 2. Let result be the empty string.
    var result: ak.StringBuilder
    ak.string_builder_construct(&result)

    # 3. Let index be 0.
    # 4. While index is less than input’s length:
    for c in ak.string_base_bytes(&input.string_base):
        # 1. Let c be input[index].
        # 2. Increment index by 1.

        # 3. If c is one of:
        #     * U+002B (+);
        #     * U+002A (*);
        #     * U+003F (?);
        #     * U+003A (:);
        #     * U+007B ({);
        #     * U+007D (});
        #     * U+0028 (();
        #     * U+0029 ()); or
        #     * U+005C (\),
        #    then append U+005C (\) to the end of result.
        if literal_contains("+*?:{}()\\", c):
            ak.string_builder_append_u8(&result, '\\')

        # 4. Append c to the end of result.
        ak.string_builder_append_u8(&result, c)

    # 5. Return result.
    return ak.string_builder_to_string_without_validation(&result)

## Ported from Libraries/LibURL/Pattern/String.cpp:51 URL::Pattern::escape_a_regexp_string.
# https://urlpattern.spec.whatwg.org/#escape-a-regexp-string
pub func pattern_escape_a_regexp_string(input: ak.String) -> ak.String:
    # 1. Assert: input is an ASCII string.
    assert(ak.string_is_ascii(&input))

    # 2. Let result be the empty string.
    var builder: ak.StringBuilder
    ak.string_builder_construct(&builder)

    # 3. Let index be 0.
    # 4. While index is less than input’s length:
    for c in ak.string_base_bytes(&input.string_base):
        # 1. Let c be input[index].
        # 2. Increment index by 1.

        # 3. If c is one of:
        #     * U+002E (.);
        #     * U+002B (+);
        #     * U+002A (*);
        #     * U+003F (?);
        #     * U+005E (^);
        #     * U+0024 ($);
        #     * U+007B ({);
        #     * U+007D (});
        #     * U+0028 (();
        #     * U+0029 ());
        #     * U+005B ([);
        #     * U+005D (]);
        #     * U+007C (|);
        #     * U+002F (/); or
        #     * U+005C (\),
        #    then append "\" to the end of result.
        if literal_contains(".+*?^${}()[]|/\\", c):
            ak.string_builder_append_u8(&builder, '\\')

        # 4. Append c to the end of result.
        ak.string_builder_append_u8(&builder, c)

    # 5. Return result.
    return ak.string_builder_to_string_without_validation(&builder)

## Ported from Libraries/LibURL/Pattern/String.cpp:94 URL::Pattern::generate_a_segment_wildcard_regexp.
# https://urlpattern.spec.whatwg.org/#generate-a-segment-wildcard-regexp
pub func pattern_generate_a_segment_wildcard_regexp(options: Options) -> ak.String:
    # 1. Let result be "[^".
    var result: ak.StringBuilder
    ak.string_builder_construct(&result)
    append_literal(&result, "[^")

    # 2. Append the result of running escape a regexp string given options’s delimiter code point to the end of result.
    if let delimiter = options.delimiter_code_point:
        append_string(&result, pattern_escape_a_regexp_string(ak.string_from_code_point(delimiter)))

    # 3. Append "]+?" to the end of result.
    append_literal(&result, "]+?")

    # 4. Return result.
    return ak.string_builder_to_string_without_validation(&result)

# part != String::from_code_point(*options.prefix_code_point), for a present prefix code point.
func string_is_not_code_point(string: ak.String, code_point: u8) -> bool:
    return not string_equals(string, ak.string_from_code_point(code_point))

# *string.code_points().begin(): the first code point of a string.
func first_code_point(string: ak.String) -> u32:
    let code_points = ak.string_code_points(&string)
    let begin = ak.utf8_view_begin(&code_points)
    return ak.utf8_code_point_iterator_deref(&begin)

## Ported from Libraries/LibURL/Pattern/String.cpp:112 URL::Pattern::generate_a_pattern_string.
# https://urlpattern.spec.whatwg.org/#generate-a-pattern-string
pub func pattern_generate_a_pattern_string(part_list: const ak.Vector[Part]*, options: Options) -> ak.String:
    # 1. Let result be the empty string.
    var result: ak.StringBuilder
    ak.string_builder_construct(&result)

    # 2. Let index list be the result of getting the indices for part list.
    # 3. For each index of index list:
    for index in 0..<ak.vector_size(part_list):
        # 1. Let part be part list[index].
        let part = ak.vector_at_const(part_list, index)

        # 2. Let previous part be part list[index - 1] if index is greater than 0, otherwise let it be null.
        let previous_part: const Part*? = ak.vector_at_const(part_list, index - 1) if index > 0 else none

        # 3. Let next part be part list[index + 1] if index is less than index list’s size - 1, otherwise let it be null.
        let next_part: const Part*? = ak.vector_at_const(part_list, index + 1) if index + 1 < ak.vector_size(part_list) else none

        # 4. If part’s type is "fixed-text" then:
        if part.type_ == PartType.fixed_text:
            # 1. If part’s modifier is "none" then:
            if part.modifier == PartModifier.none_:
                # 1. Append the result of running escape a pattern string given part’s value to the end of result.
                append_string(&result, pattern_escape_a_pattern_string(part.value))

                # 2. Continue.
                continue

            # 2. Append "{" to the end of result.
            ak.string_builder_append_u8(&result, '{')

            # 3. Append the result of running escape a pattern string given part’s value to the end of result.
            append_string(&result, pattern_escape_a_pattern_string(part.value))

            # 4. Append "}" to the end of result.
            ak.string_builder_append_u8(&result, '}')

            # 5. Append the result of running convert a modifier to a string given part’s modifier to the end of result.
            ak.string_builder_append_string_view(&result, part_convert_modifier_to_string(part.modifier))

            # 6. Continue.
            continue

        # 5. Let custom name be true if part’s name[0] is not an ASCII digit; otherwise false.
        let custom_name = not ak.is_ascii_digit(ak.string_base_bytes(&part.name.string_base)[0])

        # 6. Let needs grouping be true if at least one of the following are true, otherwise let it be false:
        #     * part’s suffix is not the empty string.
        #     * part’s prefix is not the empty string and is not options’s prefix code point.
        var needs_grouping = (not ak.string_is_empty(&part.suffix) or (not ak.string_is_empty(&part.prefix) and (options.prefix_code_point != none and string_is_not_code_point(part.prefix, options.prefix_code_point else trap("unreachable")))))

        # 7. If all of the following are true:
        #     * needs grouping is false; and
        #     * custom name is true; and
        #     * part’s type is "segment-wildcard"; and
        #     * part’s modifier is "none"; and
        #     * next part is not null; and
        #     * next part’s prefix is the empty string; and
        #     * next part’s suffix is the empty string
        #    then:
        if not needs_grouping and custom_name and part.type_ == PartType.segment_wildcard and part.modifier == PartModifier.none_:
            if let next = next_part:
                if ak.string_is_empty(&next.prefix) and ak.string_is_empty(&next.suffix):
                    # 1. If next part’s type is "fixed-text":
                    if next.type_ == PartType.fixed_text:
                        # 1. Set needs grouping to true if the result of running is a valid name code point given next part’s
                        #    value's first code point and the boolean false is true.
                        # FIXME: Raise spec bug, the language here is weird.
                        needs_grouping = tokenizer_is_a_valid_name_code_point(first_code_point(next.value), false)
                    # 2. Otherwise:
                    else:
                        # 1. Set needs grouping to true if next part’s name[0] is an ASCII digit.
                        needs_grouping = ak.is_ascii_digit(first_code_point(next.name))

        # 8. If all of the following are true:
        #     * needs grouping is false; and
        #     * part’s prefix is the empty string; and
        #     * previous part is not null; and
        #     * previous part’s type is "fixed-text"; and
        #     * previous part’s value's last code point is options’s prefix code point.
        #    then set needs grouping to true.
        if not needs_grouping and ak.string_is_empty(&part.prefix):
            if let previous = previous_part:
                if (previous.type_ == PartType.fixed_text and ((ak.string_is_empty(&previous.value) and options.prefix_code_point == none) or (options.prefix_code_point != none and not string_is_not_code_point(previous.value, options.prefix_code_point else trap("unreachable"))))):
                    needs_grouping = true

        # 9. Assert: part’s name is not the empty string or null.
        assert(not ak.string_is_empty(&part.name))

        # 10. If needs grouping is true, then append "{" to the end of result.
        if needs_grouping:
            ak.string_builder_append_u8(&result, '{')

        # 11. Append the result of running escape a pattern string given part’s prefix to the end of result.
        append_string(&result, pattern_escape_a_pattern_string(part.prefix))

        # 12. If custom name is true:
        if custom_name:
            # 1. Append ":" to the end of result.
            ak.string_builder_append_u8(&result, ':')

            # 2. Append part’s name to the end of result.
            append_string(&result, part.name)

        # 13. If part’s type is "regexp" then:
        if part.type_ == PartType.regexp:
            # 1. Append "(" to the end of result.
            ak.string_builder_append_u8(&result, '(')

            # 2. Append part’s value to the end of result.
            append_string(&result, part.value)

            # 3. Append ")" to the end of result.
            ak.string_builder_append_u8(&result, ')')
        # 14. Otherwise if part’s type is "segment-wildcard" and custom name is false:
        elif part.type_ == PartType.segment_wildcard and not custom_name:
            # 1. Append "(" to the end of result.
            ak.string_builder_append_u8(&result, '(')

            # 2. Append the result of running generate a segment wildcard regexp given options to the end of result.
            append_string(&result, pattern_generate_a_segment_wildcard_regexp(options))

            # 3. Append ")" to the end of result.
            ak.string_builder_append_u8(&result, ')')
        # 15. Otherwise if part’s type is "full-wildcard":
        elif part.type_ == PartType.full_wildcard:
            # 1. If custom name is false and one of the following is true:
            #     * previous part is null; or
            #     * previous part’s type is "fixed-text"; or
            #     * previous part’s modifier is not "none"; or
            #     * needs grouping is true; or
            #     * part’s prefix is not the empty string
            #    then append "*" to the end of result.
            if (not custom_name and (previous_part == none or (previous_part else trap("unreachable")).type_ == PartType.fixed_text or (previous_part else trap("unreachable")).modifier != PartModifier.none_ or needs_grouping or not ak.string_is_empty(&part.prefix))):
                ak.string_builder_append_u8(&result, '*')
            # 2. Otherwise:
            else:
                # 1. Append "(" to the end of result.
                ak.string_builder_append_u8(&result, '(')

                # 2. Append full wildcard regexp value to the end of result.
                append_literal(&result, pattern_full_wildcard_regexp_value)

                # 3. Append ")" to the end of result.
                ak.string_builder_append_u8(&result, ')')

        # 16. If all of the following are true:
        #      * part’s type is "segment-wildcard"; and
        #      * custom name is true; and
        #      * part’s suffix is not the empty string; and
        #      * The result of running is a valid name code point given part’s suffix's first code point and the boolean false is true
        #     then append U+005C (\) to the end of result.
        if (part.type_ == PartType.segment_wildcard and custom_name and not ak.string_is_empty(&part.suffix) and tokenizer_is_a_valid_name_code_point(first_code_point(part.suffix), false)):
            ak.string_builder_append_u8(&result, '\\')

        # 17. Append the result of running escape a pattern string given part’s suffix to the end of result.
        append_string(&result, pattern_escape_a_pattern_string(part.suffix))

        # 18. If needs grouping is true, then append "}" to the end of result.
        if needs_grouping:
            ak.string_builder_append_u8(&result, '}')

        # 19. Append the result of running convert a modifier to a string given part’s modifier to the end of result.
        ak.string_builder_append_string_view(&result, part_convert_modifier_to_string(part.modifier))

    # 4. Return result.
    return ak.string_builder_to_string_without_validation(&result)