Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / html / parser / html_parser_3.lucb

#==============================================================================================
#
#   html_parser_3 - HTML::HTMLParser: the "in head", "in head noscript" and "after head"
#                   insertion modes and character insertion
#
#   DESCRIPTION:
#       Port of LibWeb/HTML/Parser/HTMLParser.cpp (lines 1134-1727): the "in head" insertion
#       mode (with <script> preparation and declarative shadow roots on <template>), "in head
#       noscript", the generic raw text element parsing algorithm, the buffered character
#       insertion (characters are collected in a UTF-16 builder and written to their Text node
#       when the insertion node changes or the parser stops), the element-popped hook and the
#       "after head" insertion mode.
#
#==============================================================================================

# mark: The in head insertion mode ==============================================================

## Ported from HTMLParser.cpp:1135 Web::HTML::HTMLParser::handle_in_head.
# https://html.spec.whatwg.org/multipage/parsing.html#parsing-main-inhead
pub func html_parser_handle_in_head(this: HtmlParser*, token: html_syntax.HtmlToken*):
    # -> A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF),
    #    U+000D CARRIAGE RETURN (CR), or U+0020 SPACE
    if html_syntax.html_token_is_parser_whitespace(token):
        # Insert the character.
        html_parser_insert_character(this, html_syntax.html_token_code_point(token))
        return

    # -> A comment token
    if html_syntax.html_token_is_comment(token):
        # Insert a comment.
        html_parser_insert_comment(this, token)
        return

    # -> A DOCTYPE token
    if html_syntax.html_token_is_doctype(token):
        # Parse error. Ignore the token.
        html_log_parse_error()
        return

    # -> A start tag whose tag name is "html"
    if html_syntax.html_token_is_start_tag(token) and html_parser_tag_name_is(token, html_tag_names_html):
        # Process the token using the rules for the "in body" insertion mode.
        html_parser_process_using_the_rules_for(this, HtmlParserInsertionMode.in_body, token)
        return

    # -> A start tag whose tag name is one of: "base", "basefont", "bgsound", "link"
    if html_syntax.html_token_is_start_tag(token) and html_parser_tag_name_is_one_of(token, [html_tag_names_base, html_tag_names_basefont, html_tag_names_bgsound, html_tag_names_link]):
        # Insert an HTML element for the token. Immediately pop the current node off the stack of open elements.
        _ = html_parser_insert_html_element(this, token)
        _ = html_stack_of_open_elements_pop(&this.m_stack_of_open_elements)

        # Acknowledge the token's self-closing flag, if it is set.
        html_syntax.html_token_acknowledge_self_closing_flag_if_set(token)
        return

    # -> A start tag whose tag name is "meta"
    if html_syntax.html_token_is_start_tag(token) and html_parser_tag_name_is(token, html_tag_names_meta):
        # Insert an HTML element for the token. Immediately pop the current node off the stack of open elements.
        _ = html_parser_insert_html_element(this, token)
        _ = html_stack_of_open_elements_pop(&this.m_stack_of_open_elements)

        # Acknowledge the token's self-closing flag, if it is set.
        html_syntax.html_token_acknowledge_self_closing_flag_if_set(token)

        # FIXME: If the active speculative HTML parser is null, then:
        #        ...
        return

    # -> A start tag whose tag name is "title"
    if html_syntax.html_token_is_start_tag(token) and html_parser_tag_name_is(token, html_tag_names_title):
        # Follow the generic RCDATA element parsing algorithm.
        # FIXME: Pull this out into a separate method.
        _ = html_parser_insert_html_element(this, token)
        html_syntax.html_tokenizer_switch_to_html_parser(&this.m_tokenizer, html_syntax.HtmlTokenizerState.rcdata)
        this.m_original_insertion_mode = this.m_insertion_mode
        this.m_insertion_mode = HtmlParserInsertionMode.text
        return

    # -> A start tag whose tag name is "noscript", if scripting mode is not Disabled
    # -> A start tag whose tag name is one of: "noframes", "style"
    if html_syntax.html_token_is_start_tag(token) and ((html_parser_tag_name_is(token, html_tag_names_noscript) and this.m_scripting_mode != HtmlParserScriptingMode.disabled) or html_parser_tag_name_is(token, html_tag_names_noframes) or html_parser_tag_name_is(token, html_tag_names_style)):
        # Follow the generic raw text element parsing algorithm.
        html_parser_parse_generic_raw_text_element(this, token)
        return

    # -> A start tag whose tag name is "noscript", if scripting mode is Disabled
    if html_syntax.html_token_is_start_tag(token) and html_parser_tag_name_is(token, html_tag_names_noscript) and this.m_scripting_mode == HtmlParserScriptingMode.disabled:
        # Insert an HTML element for the token.
        _ = html_parser_insert_html_element(this, token)

        # Switch the insertion mode to "in head noscript".
        this.m_insertion_mode = HtmlParserInsertionMode.in_head_noscript
        return

    # -> A start tag whose tag name is "script"
    if html_syntax.html_token_is_start_tag(token) and html_parser_tag_name_is(token, html_tag_names_script):
        # Run these steps:

        # 1. Let the adjusted insertion location be the appropriate place for inserting a node.
        let adjusted_insertion_location = html_parser_find_appropriate_place_for_inserting_node(this)
        let parent = adjusted_insertion_location.parent else trap("VERIFY: adjusted insertion location")

        # 2. Create an element for the token in the HTML namespace, with the intended parent being the element in
        #    which the adjusted insertion location finds itself.
        let element = html_parser_create_element_for(this, token, namespace_html, parent)
        let script_element = as_html_script_element(element)

        # 3. If the scripting mode is not Fragment, then set the element's parser document to the Document.
        # NOTE: The Fragment scripting mode treats parser-inserted scripts as if they were not parser-inserted,
        #       allowing, for example, executing scripts when applying a fragment created by createContextualFragment().
        if this.m_scripting_mode != HtmlParserScriptingMode.fragment:
            html_script_element_set_parser_document(script_element, html_parser_document(this))

        # 4. Set the element's force async to false.
        # NOTE: This ensures that, if the script is external, any document.write() calls in the script will execute
        #       in-line, instead of blowing the document away, as would happen in most other cases. It also prevents
        #       the script from executing until the end tag is seen.
        html_script_element_set_force_async(script_element, false)

        html_script_element_set_source_line_number(script_element, html_syntax.html_token_start_position(token).line + 1)  # FIXME: This +1 is incorrect for script tags whose script does not start on a new line

        # 5. If the parser's scripting mode is Inert, then set the script element's already started to true. (fragment case)
        if this.m_scripting_mode == HtmlParserScriptingMode.inert:
            html_script_element_set_already_started(script_element, true)

        # 6. If the parser was invoked via the document.write() or document.writeln() methods, then optionally set the
        #    script element's already started to true. (For example, the user agent might use this clause to prevent
        #    execution of cross-origin scripts inserted via document.write() under slow network conditions, or when
        #    the page has already taken a long time to load.)
        if this.m_invoked_via_document_write:
            trap("TODO")

        # 7. Insert the newly created element at the adjusted insertion location.
        dom_node_insert_before(parent, element.dom_node(), adjusted_insertion_location.insert_before_sibling, false)

        # 8. Push the element onto the stack of open elements so that it is the new current node.
        html_stack_of_open_elements_push(&this.m_stack_of_open_elements, element)

        # 9. Switch the tokenizer to the script data state.
        html_syntax.html_tokenizer_switch_to_html_parser(&this.m_tokenizer, html_syntax.HtmlTokenizerState.script_data)

        # 10. Set the original insertion mode to the current insertion mode.
        this.m_original_insertion_mode = this.m_insertion_mode

        # 11. Switch the insertion mode to "text".
        this.m_insertion_mode = HtmlParserInsertionMode.text
        return

    # -> An end tag whose tag name is "head"
    if html_syntax.html_token_is_end_tag(token) and html_parser_tag_name_is(token, html_tag_names_head):
        # Pop the current node (which will be the head element) off the stack of open elements.
        _ = html_stack_of_open_elements_pop(&this.m_stack_of_open_elements)

        # Switch the insertion mode to "after head".
        this.m_insertion_mode = HtmlParserInsertionMode.after_head
        return

    # -> An end tag whose tag name is one of: "body", "html", "br"
    #    Act as described in the "anything else" entry below. (goto AnythingElse)
    let anything_else = html_syntax.html_token_is_end_tag(token) and html_parser_tag_name_is_one_of(token, [html_tag_names_body, html_tag_names_html, html_tag_names_br])

    if not anything_else:
        # -> A start tag whose tag name is "template"
        if html_syntax.html_token_is_start_tag(token) and html_parser_tag_name_is(token, html_tag_names_template):
            html_parser_handle_in_head_template_start_tag(this, token)
            return

        # -> An end tag whose tag name is "template"
        if html_syntax.html_token_is_end_tag(token) and html_parser_tag_name_is(token, html_tag_names_template):
            # If there is no template element on the stack of open elements, then this is a parse error; ignore the token.
            if not html_stack_of_open_elements_contains_template_element(&this.m_stack_of_open_elements):
                html_log_parse_error()
                return

            # Otherwise, run these steps:

            # 1. Generate all implied end tags thoroughly.
            html_parser_generate_all_implied_end_tags_thoroughly(this)

            # 2. If the current node is not a template element, then this is a parse error.
            if not html_parser_local_name_is(html_parser_current_element(this), html_tag_names_template):
                html_log_parse_error()

            # 3. Pop elements from the stack of open elements until a template element has been popped from the stack.
            html_stack_of_open_elements_pop_until_an_element_with_tag_name_has_been_popped(&this.m_stack_of_open_elements, html_tag_names_template)

            # 4. Clear the list of active formatting elements up to the last marker.
            html_list_of_active_formatting_elements_clear_up_to_the_last_marker(&this.m_list_of_active_formatting_elements)

            # 5. Pop the current template insertion mode off the stack of template insertion modes.
            _ = ak.vector_take_last(&this.m_stack_of_template_insertion_modes)

            # 6. Reset the insertion mode appropriately.
            html_parser_reset_the_insertion_mode_appropriately(this)
            return

        # ->A start tag whose tag name is "head"
        # -> Any other end tag
        if (html_syntax.html_token_is_start_tag(token) and html_parser_tag_name_is(token, html_tag_names_head)) or html_syntax.html_token_is_end_tag(token):
            # Parse error. Ignore the token.
            html_log_parse_error()
            return

    # -> Anything else
    # AnythingElse:
    # Pop the current node (which will be the head element) off the stack of open elements.
    _ = html_stack_of_open_elements_pop(&this.m_stack_of_open_elements)

    # Switch the insertion mode to "after head".
    this.m_insertion_mode = HtmlParserInsertionMode.after_head

    # Reprocess the token.
    html_parser_process_using_the_rules_for(this, this.m_insertion_mode, token)

## handle_in_head's "A start tag whose tag name is "template"" entry (HTMLParser.cpp:1293-1420),
## kept apart from the rest of the insertion mode for its size.
func html_parser_handle_in_head_template_start_tag(this: HtmlParser*, token: html_syntax.HtmlToken*):
    # Run these steps:
    # 1. Let templateStartTag be the start tag.
    let template_start_tag = token

    # 2. Insert a marker at the end of the list of active formatting elements.
    html_list_of_active_formatting_elements_add_marker(&this.m_list_of_active_formatting_elements)

    # 3. Set the frameset-ok flag to "not ok".
    this.m_frameset_ok = false

    # 4. Switch the insertion mode to "in template".
    this.m_insertion_mode = HtmlParserInsertionMode.in_template

    # 5. Push "in template" onto the stack of template insertion modes so that it is the new current template
    #    insertion mode.
    ak.vector_append_t(&this.m_stack_of_template_insertion_modes, HtmlParserInsertionMode.in_template)

    # 6. Let the adjustedInsertionLocation be the appropriate place for inserting a node.
    let adjusted_insertion_location = html_parser_find_appropriate_place_for_inserting_node(this)

    # 7. Let intendedParent be the element in which the adjustedInsertionLocation finds itself.
    let intended_parent = adjusted_insertion_location.parent else trap("VERIFY: adjusted insertion location")

    # 8. Let document be intendedParent's node document.
    let document = dom_node_document(intended_parent)

    var shadowrootmode: BindShadowRootMode? = none
    if let shadowrootmode_attribute_value = html_syntax.html_token_attribute(template_start_tag, html_attribute_names_shadowrootmode):
        if ak.string_eq_string_view(&shadowrootmode_attribute_value, ak.sv("open")):
            shadowrootmode = BindShadowRootMode.open
        elif ak.string_eq_string_view(&shadowrootmode_attribute_value, ak.sv("closed")):
            shadowrootmode = BindShadowRootMode.closed

    # 9. If any of the following are false:
    #    - templateStartTag's shadowrootmode is not in the None state;
    #    - document's allow declarative shadow roots is true; or
    #    - the adjusted current node is not the topmost element in the stack of open elements,
    if shadowrootmode == none or not dom_document_allow_declarative_shadow_roots(document) or html_parser_adjusted_current_node(this) == html_stack_of_open_elements_first(&this.m_stack_of_open_elements):
        # then insert an HTML element for the token.
        _ = html_parser_insert_html_element(this, token)
        return

    # 10. Otherwise:
    # 1. Let declarativeShadowHostElement be adjusted current node.
    let declarative_shadow_host_element = html_parser_adjusted_current_node(this) else trap("VERIFY: adjusted current node")

    # 2. Let template be the result of insert a foreign element for templateStartTag, with HTML namespace and
    #    true.
    let template_ = html_parser_insert_foreign_element(this, template_start_tag, namespace_html, HtmlParserOnlyAddToElementStack.yes)

    # 3. Let mode be templateStartTag's shadowrootmode attribute's value.
    let mode = shadowrootmode else trap("checked")

    # 4. Let clonable be true if templateStartTag has a shadowrootclonable attribute; otherwise false.
    let clonable = html_syntax.html_token_has_attribute(template_start_tag, html_attribute_names_shadowrootclonable)

    # 5. Let serializable be true if templateStartTag has a shadowrootserializable attribute; otherwise false.
    let serializable = html_syntax.html_token_has_attribute(template_start_tag, html_attribute_names_shadowrootserializable)

    # 6. Let delegatesFocus be true if templateStartTag has a shadowrootdelegatesfocus attribute; otherwise
    #    false.
    let delegates_focus = html_syntax.html_token_has_attribute(template_start_tag, html_attribute_names_shadowrootdelegatesfocus)

    # 7. If declarativeShadowHostElement is a shadow host, then insert an element at the adjusted insertion
    #    location with template.
    if dom_element_is_shadow_host(declarative_shadow_host_element):
        # FIXME: We do manual "insert before" instead of "insert an element at the adjusted insertion location" here
        #        Otherwise, two template elements in a row will cause the second to try to insert into itself.
        #        This might be a spec bug(?)
        dom_node_insert_before(intended_parent, template_.dom_node(), adjusted_insertion_location.insert_before_sibling)
        return

    # 8. Otherwise:
    # 1. Let registry be null if templateStartTag has a shadowrootcustomelementregistry attribute;
    #    otherwise declarativeShadowHostElement's node document's custom element registry.
    var registry: HtmlCustomElementRegistry*? = none
    if not html_syntax.html_token_has_attribute(template_start_tag, html_attribute_names_shadowrootcustomelementregistry):
        registry = dom_document_custom_element_registry(dom_node_document(declarative_shadow_host_element.dom_node()))

    # 2. Attach a shadow root with declarativeShadowHostElement, mode, clonable, serializable,
    #    delegatesFocus, "named", and registry.
    var attached = true
    dom_element_attach_a_shadow_root(declarative_shadow_host_element, mode, clonable, serializable, delegates_focus, BindSlotAssignmentMode.named, registry) catch:
        attached = false
        recover ()
    #    If an exception is thrown, then catch it and:
    if not attached:
        # 1. Insert an element at the adjusted insertion location with template.
        # FIXME: We do manual "insert before" instead of "insert an element at the adjusted insertion location" here
        #        Otherwise, the new insertion location will be inside the template's contents, which is not what we want here.
        #        This might be a spec bug(?)
        dom_node_insert_before(intended_parent, template_.dom_node(), adjusted_insertion_location.insert_before_sibling)

        # 2. The user agent may report an error to the developer console.
        let vm = js_cell_vm(this.js_cell())
        html_report_exception_js_completion(bind_exception_to_throw_completion(vm, vm_take_pending_exception(vm)), html_parser_realm(this))

        # 3. Return.
        return

    # 3. Let shadow be declarativeShadowHostElement's shadow root.
    let shadow = dom_element_shadow_root(declarative_shadow_host_element) else trap("VERIFY: shadow root")

    # 4. Set shadow's declarative to true.
    dom_shadow_root_set_declarative(shadow, true)

    # 5. Set template's template contents to shadow.
    html_template_element_set_template_contents(as_html_template_element(template_), shadow.dom_document_fragment())

    # 6. Set shadow's available to element internals to true.
    dom_shadow_root_set_available_to_element_internals(shadow, true)

    # 7. If templateStartTag has a shadowrootcustomelementregistry attribute, then set shadow's keep
    #    custom element registry null to true.
    if html_syntax.html_token_has_attribute(template_start_tag, html_attribute_names_shadowrootcustomelementregistry):
        dom_shadow_root_set_keep_custom_element_registry_null(shadow, true)

## Ported from HTMLParser.cpp:1476 Web::HTML::HTMLParser::handle_in_head_noscript.
# https://html.spec.whatwg.org/multipage/parsing.html#parsing-main-inheadnoscript
pub func html_parser_handle_in_head_noscript(this: HtmlParser*, token: html_syntax.HtmlToken*):
    # -> A DOCTYPE token
    if html_syntax.html_token_is_doctype(token):
        # Parse error. Ignore the token.
        html_log_parse_error()
        return

    # -> A start tag whose tag name is "html"
    if html_syntax.html_token_is_start_tag(token) and html_parser_tag_name_is(token, html_tag_names_html):
        # Process the token using the rules for the "in body" insertion mode.
        html_parser_process_using_the_rules_for(this, HtmlParserInsertionMode.in_body, token)
        return

    # -> An end tag whose tag name is "noscript"
    if html_syntax.html_token_is_end_tag(token) and html_parser_tag_name_is(token, html_tag_names_noscript):
        # Pop the current node (which will be a noscript element) from the stack of open elements;
        # the new current node will be a head element.
        _ = html_stack_of_open_elements_pop(&this.m_stack_of_open_elements)

        # Switch the insertion mode to "in head".
        this.m_insertion_mode = HtmlParserInsertionMode.in_head
        return

    # -> A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE
    # -> A comment token
    # -> A start tag whose tag name is one of: "basefont", "bgsound", "link", "meta", "noframes", "style"
    if html_syntax.html_token_is_parser_whitespace(token) or html_syntax.html_token_is_comment(token) or (html_syntax.html_token_is_start_tag(token) and html_parser_tag_name_is_one_of(token, [html_tag_names_basefont, html_tag_names_bgsound, html_tag_names_link, html_tag_names_meta, html_tag_names_noframes, html_tag_names_style])):
        # Process the token using the rules for the "in head" insertion mode.
        html_parser_process_using_the_rules_for(this, HtmlParserInsertionMode.in_head, token)
        return

    # -> An end tag whose tag name is "br"
    #    Act as described in the "anything else" entry below. (goto AnythingElse)
    let anything_else = html_syntax.html_token_is_end_tag(token) and html_parser_tag_name_is(token, html_tag_names_br)

    # -> A start tag whose tag name is one of: "head", "noscript"
    # -> Any other end tag
    if not anything_else and ((html_syntax.html_token_is_start_tag(token) and html_parser_tag_name_is_one_of(token, [html_tag_names_head, html_tag_names_noscript])) or html_syntax.html_token_is_end_tag(token)):
        # Parse error. Ignore the token.
        html_log_parse_error()
        return

    # -> Anything else
    # AnythingElse:
    # Parse error.
    html_log_parse_error()

    # Pop the current node (which will be a noscript element) from the stack of open elements; the new current node will be a head element.
    _ = html_stack_of_open_elements_pop(&this.m_stack_of_open_elements)

    # Switch the insertion mode to "in head".
    this.m_insertion_mode = HtmlParserInsertionMode.in_head

    # Reprocess the token.
    html_parser_process_using_the_rules_for(this, this.m_insertion_mode, token)

## Ported from HTMLParser.cpp:1546 Web::HTML::HTMLParser::parse_generic_raw_text_element.
pub func html_parser_parse_generic_raw_text_element(this: HtmlParser*, token: html_syntax.HtmlToken*):
    _ = html_parser_insert_html_element(this, token)
    html_syntax.html_tokenizer_switch_to_html_parser(&this.m_tokenizer, html_syntax.HtmlTokenizerState.rawtext)
    this.m_original_insertion_mode = this.m_insertion_mode
    this.m_insertion_mode = HtmlParserInsertionMode.text

# mark: Character insertion =====================================================================

## Ported from HTMLParser.cpp:1554 Web::HTML::is_text_node.
func html_is_text_node(node: DomNode*?) -> bool:
    let actual_node = node else return false
    return dom_node_is_text(actual_node)

## Ported from HTMLParser.cpp:1559 Web::HTML::HTMLParser::find_character_insertion_node.
pub func html_parser_find_character_insertion_node(this: HtmlParser*) -> DomText*?:
    let adjusted_insertion_location = html_parser_find_appropriate_place_for_inserting_node(this)
    let parent = adjusted_insertion_location.parent else trap("VERIFY: adjusted insertion location")
    if let insert_before_sibling = adjusted_insertion_location.insert_before_sibling:
        let previous_sibling = tree_node_previous_sibling(insert_before_sibling)
        if html_is_text_node(previous_sibling):
            return (DomText*?)previous_sibling
        let new_text_node = realm_create_dom_text_utf16_string(html_parser_realm(this), html_parser_document(this), ak.utf16_string_new())
        dom_node_insert_before(parent, new_text_node.dom_node(), insert_before_sibling)
        return new_text_node
    if dom_node_is_document(parent):
        return none
    let last_child = tree_node_last_child(parent)
    if html_is_text_node(last_child):
        return (DomText*?)last_child
    let new_text_node = realm_create_dom_text_utf16_string(html_parser_realm(this), html_parser_document(this), ak.utf16_string_new())
    _ = dom_node_append_child(parent, new_text_node.dom_node()) else trap("MUST: append_child")
    return new_text_node

## Ported from HTMLParser.cpp:1578 Web::HTML::HTMLParser::flush_character_insertions.
pub func html_parser_flush_character_insertions(this: HtmlParser*):
    if ak.string_builder_is_empty(&this.m_character_insertion_builder):
        return
    let node = (this.m_character_insertion_node else trap("VERIFY: character insertion node")).dom_character_data()
    let data = dom_character_data_data(node)
    if ak.utf16_string_base_is_empty(&data.utf16_string_base):
        dom_character_data_set_data(node, ak.string_builder_to_utf16_string(&this.m_character_insertion_builder))
    else:
        let appended = ak.string_builder_to_utf16_string(&this.m_character_insertion_builder)
        dom_character_data_append_data(node, ak.utf16_string_base_utf16_view(&appended.utf16_string_base)) catch:
            # (void): the C++ drops the result.
            _ = idl_take_pending_exception()
            recover ()
    ak.string_builder_clear(&this.m_character_insertion_builder)

## Ported from HTMLParser.cpp:1589 Web::HTML::HTMLParser::handle_element_popped.
pub func html_parser_handle_element_popped(this: HtmlParser*, element: DomElement*):
    # https://html.spec.whatwg.org/multipage/form-elements.html#the-option-element
    # When an option element is popped off the stack of open elements of an HTML parser or XML parser,
    # the user agent must run maybe clone an option into selectedcontent given the option element.
    if let option_element = as_if_html_option_element(element):
        # AD-HOC: Flush buffered text so the option's content is up-to-date before cloning.
        html_parser_flush_character_insertions(this)

        html_option_element_maybe_clone_into_selectedcontent(option_element) else trap("MUST: maybe_clone_into_selectedcontent")

## Ported from HTMLParser.cpp:1602 Web::HTML::HTMLParser::insert_character.
pub func html_parser_insert_character(this: HtmlParser*, data: u32):
    let node = html_parser_find_character_insertion_node(this)
    if node == this.m_character_insertion_node:
        ak.string_builder_append_code_point(&this.m_character_insertion_builder, data)
        return
    if this.m_character_insertion_node == none:
        this.m_character_insertion_node = node
        ak.string_builder_append_code_point(&this.m_character_insertion_builder, data)
        return
    html_parser_flush_character_insertions(this)
    this.m_character_insertion_node = node
    ak.string_builder_append_code_point(&this.m_character_insertion_builder, data)

# mark: The after head insertion mode ===========================================================

## Ported from HTMLParser.cpp:1620 Web::HTML::HTMLParser::handle_after_head.
# https://html.spec.whatwg.org/multipage/parsing.html#the-after-head-insertion-mode
pub func html_parser_handle_after_head(this: HtmlParser*, token: html_syntax.HtmlToken*):
    # -> A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF),
    #    U+000D CARRIAGE RETURN (CR), or U+0020 SPACE
    if html_syntax.html_token_is_character(token) and html_syntax.html_token_is_parser_whitespace(token):
        # Insert the character.
        html_parser_insert_character(this, html_syntax.html_token_code_point(token))
        return

    # -> A comment token
    if html_syntax.html_token_is_comment(token):
        # Insert a comment.
        html_parser_insert_comment(this, token)
        return

    # -> A DOCTYPE token
    if html_syntax.html_token_is_doctype(token):
        # Parse error. Ignore the token.
        html_log_parse_error()
        return

    # -> A start tag whose tag name is "html"
    if html_syntax.html_token_is_start_tag(token) and html_parser_tag_name_is(token, html_tag_names_html):
        # Process the token using the rules for the "in body" insertion mode.
        html_parser_process_using_the_rules_for(this, HtmlParserInsertionMode.in_body, token)
        return

    # -> A start tag whose tag name is "body"
    if html_syntax.html_token_is_start_tag(token) and html_parser_tag_name_is(token, html_tag_names_body):
        # Insert an HTML element for the token.
        _ = html_parser_insert_html_element(this, token)

        # Set the frameset-ok flag to "not ok".
        this.m_frameset_ok = false

        # Switch the insertion mode to "in body".
        this.m_insertion_mode = HtmlParserInsertionMode.in_body
        return

    # -> A start tag whose tag name is "frameset"
    if html_syntax.html_token_is_start_tag(token) and html_parser_tag_name_is(token, html_tag_names_frameset):
        # Insert an HTML element for the token.
        _ = html_parser_insert_html_element(this, token)

        # Switch the insertion mode to "in frameset".
        this.m_insertion_mode = HtmlParserInsertionMode.in_frameset
        return

    # -> A start tag whose tag name is one of: "base", "basefont", "bgsound", "link", "meta", "noframes", "script",
    #    "style", "template", "title"
    if html_syntax.html_token_is_start_tag(token) and html_parser_tag_name_is_one_of(token, [html_tag_names_base, html_tag_names_basefont, html_tag_names_bgsound, html_tag_names_link, html_tag_names_meta, html_tag_names_noframes, html_tag_names_script, html_tag_names_style, html_tag_names_template, html_tag_names_title]):
        # Parse error.
        html_log_parse_error()

        # Push the node pointed to by the head element pointer onto the stack of open elements.
        let head_element = (this.m_head_element else trap("VERIFY: head element pointer")).dom_element()
        html_stack_of_open_elements_push(&this.m_stack_of_open_elements, head_element)

        # Process the token using the rules for the "in head" insertion mode.
        html_parser_process_using_the_rules_for(this, HtmlParserInsertionMode.in_head, token)

        # Remove the node pointed to by the head element pointer from the stack of open elements.
        # (It might not be the current node at this point.)
        html_parser_remove_first_element(&this.m_stack_of_open_elements.m_elements, head_element)
        return

    # -> An end tag whose tag name is "template"
    if html_syntax.html_token_is_end_tag(token) and html_parser_tag_name_is(token, html_tag_names_template):
        # Process the token using the rules for the "in head" insertion mode.
        html_parser_process_using_the_rules_for(this, HtmlParserInsertionMode.in_head, token)
        return

    # -> An end tag whose tag name is one of: "body", "html", "br"
    #    Act as described in the "anything else" entry below. (goto AnythingElse)
    let anything_else = html_syntax.html_token_is_end_tag(token) and html_parser_tag_name_is_one_of(token, [html_tag_names_body, html_tag_names_html, html_tag_names_br])

    # -> A start tag whose tag name is "head"
    # -> Any other end tag
    if not anything_else and ((html_syntax.html_token_is_start_tag(token) and html_parser_tag_name_is(token, html_tag_names_head)) or html_syntax.html_token_is_end_tag(token)):
        # Parse error. Ignore the token.
        html_log_parse_error()
        return

    # -> Anything else
    # AnythingElse:
    # Insert an HTML element for a "body" start tag token with no attributes.
    _ = html_parser_insert_html_element_for_tag_name(this, html_tag_names_body)

    # Switch the insertion mode to "in body".
    this.m_insertion_mode = HtmlParserInsertionMode.in_body

    # Reprocess the current token.
    html_parser_process_using_the_rules_for(this, this.m_insertion_mode, token)