Skip to content

Truly independent web browser

16.8 KB
Raw Blame
/*
 * Copyright (c) 2026-present, the Ladybird developers.
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

pub mod code_units;
pub mod entities;
pub mod fragment;
mod known_names;
pub mod meta_charset_scanner;
pub mod parser;
pub mod preload_scanner;
mod scan;
pub mod token;
pub mod tokenizer;

use ak::Utf16View;
use std::ptr;
use token::Attribute;
use token::Position;
use token::SourceOffset;
use token::TokenPayload;
use token::TokenType;
use tokenizer::HtmlTokenizer;
use tokenizer::State;

/// Opaque handle for the Rust tokenizer, passed across the FFI boundary.
pub struct RustFfiTokenizerHandle {
    pub(crate) tokenizer: HtmlTokenizer,
    /// Temporary storage for the last token's string data, kept alive
    /// so that pointers in RustFfiToken remain valid until the next call.
    last_tag_name: token::HtmlName,
    last_comment: Vec<u16>,
    last_doctype_name: Vec<u16>,
    last_public_id: Vec<u16>,
    last_system_id: Vec<u16>,
    last_attributes: Vec<RustFfiAttribute>,
    last_attr_names: Vec<token::HtmlName>,
    last_attr_values: Vec<Vec<u16>>,
    last_unparsed_input: Vec<u16>,
}

/// C-compatible token representation.
///
/// Pointer fields borrow into buffers owned by the `RustFfiTokenizerHandle` that
/// produced this token. They remain valid only until the next call into the
/// tokenizer for that handle (any of `next_token`, `insert_input`, `destroy`,
/// etc.). Callers must consume the data before making the next call.
#[repr(C)]
pub struct RustFfiToken {
    pub token_type: u8,
    pub code_point: u32,
    pub self_closing: bool,
    pub had_duplicate_attribute: bool,

    /// Borrowed `AK::Utf16FlyString` identity owned by the tokenizer handle.
    pub tag_name: usize,

    pub comment_ptr: *const u16,
    pub comment_len: usize,

    pub doctype_name_ptr: *const u16,
    pub doctype_name_len: usize,
    pub public_id_ptr: *const u16,
    pub public_id_len: usize,
    pub system_id_ptr: *const u16,
    pub system_id_len: usize,
    pub force_quirks: bool,
    pub missing_name: bool,
    pub missing_public_id: bool,
    pub missing_system_id: bool,

    pub attributes_ptr: *const RustFfiAttribute,
    pub attributes_len: usize,

    pub start_line: u64,
    pub start_column: u64,
    pub end_line: u64,
    pub end_column: u64,
}

/// C-compatible attribute representation.
#[repr(C)]
pub struct RustFfiAttribute {
    /// Borrowed `AK::Utf16FlyString` identity owned by the tokenizer handle.
    pub name: usize,
    pub value_ptr: *const u16,
    pub value_len: usize,
    pub name_start_line: u64,
    pub name_start_column: u64,
    pub name_end_line: u64,
    pub name_end_column: u64,
    pub value_start_line: u64,
    pub value_start_column: u64,
    pub value_end_line: u64,
    pub value_end_column: u64,
}

impl Default for RustFfiToken {
    fn default() -> Self {
        RustFfiToken {
            token_type: TokenType::Invalid as u8,
            code_point: 0,
            self_closing: false,
            had_duplicate_attribute: false,
            tag_name: 0,
            comment_ptr: ptr::null(),
            comment_len: 0,
            doctype_name_ptr: ptr::null(),
            doctype_name_len: 0,
            public_id_ptr: ptr::null(),
            public_id_len: 0,
            system_id_ptr: ptr::null(),
            system_id_len: 0,
            force_quirks: false,
            missing_name: true,
            missing_public_id: true,
            missing_system_id: true,
            attributes_ptr: ptr::null(),
            attributes_len: 0,
            start_line: 0,
            start_column: 0,
            end_line: 0,
            end_column: 0,
        }
    }
}

fn position_to_ffi(pos: Position) -> (u64, u64) {
    (pos.line, pos.column)
}

/// Create a new Rust HTML tokenizer directly from a UTF-16 code unit buffer.
#[unsafe(no_mangle)]
pub extern "C" fn rust_html_tokenizer_create_from_utf16(input: ak::Span<'_, u16>) -> *mut RustFfiTokenizerHandle {
    make_handle(HtmlTokenizer::new(input.as_slice().to_vec()))
}

/// Create a new Rust HTML tokenizer directly from a Latin-1 byte buffer.
#[unsafe(no_mangle)]
pub extern "C" fn rust_html_tokenizer_create_from_latin1(input: ak::Span<'_, u8>) -> *mut RustFfiTokenizerHandle {
    make_handle(HtmlTokenizer::new(input.as_slice().to_vec()))
}

fn make_handle(tokenizer: HtmlTokenizer) -> *mut RustFfiTokenizerHandle {
    let handle = Box::new(RustFfiTokenizerHandle {
        tokenizer,
        last_tag_name: Default::default(),
        last_comment: Vec::new(),
        last_doctype_name: Vec::new(),
        last_public_id: Vec::new(),
        last_system_id: Vec::new(),
        last_attributes: Vec::new(),
        last_attr_names: Vec::new(),
        last_attr_values: Vec::new(),
        last_unparsed_input: Vec::new(),
    });

    Box::into_raw(handle)
}

/// Get the next token from the tokenizer.
/// Returns true if a token was produced, false if no more tokens.
#[unsafe(no_mangle)]
pub extern "C" fn rust_html_tokenizer_next_token(
    handle: Option<&mut RustFfiTokenizerHandle>,
    out: Option<&mut RustFfiToken>,
    stop_at_insertion_point: bool,
    cdata_allowed: bool,
) -> bool {
    let Some(handle) = handle else {
        return false;
    };
    let Some(out) = out else {
        return false;
    };

    // Fast-path text character in the Data state. For ASCII text runs
    // this skips the whole state-machine function call plus Token
    // construction/drop. Most real HTML is dominated by such runs.
    if !stop_at_insertion_point && let Some(cp) = handle.tokenizer.try_fast_data_char() {
        let offset = SourceOffset::new(handle.tokenizer.current_offset);
        let pos = handle.tokenizer.position_at(offset);
        out.token_type = TokenType::Character as u8;
        out.code_point = cp;
        out.start_line = pos.line;
        out.start_column = pos.column;
        out.end_line = pos.line;
        out.end_column = pos.column;
        return true;
    }

    next_token_slow(handle, out, stop_at_insertion_point, cdata_allowed)
}

/// The state-machine and marshalling portion of the FFI token fetch,
/// pulled out of `rust_html_tokenizer_next_token` so that the fast
/// Data-state path in the outer function keeps a tiny stack frame
/// and a short prologue. Marked `#[inline(never)]` so the compiler
/// doesn't re-inline the whole thing and re-inflate the outer frame.
#[inline(never)]
fn next_token_slow(
    handle: &mut RustFfiTokenizerHandle,
    out: &mut RustFfiToken,
    stop_at_insertion_point: bool,
    cdata_allowed: bool,
) -> bool {
    let token = match handle.tokenizer.next_token(stop_at_insertion_point, cdata_allowed) {
        Some(t) => t,
        None => return false,
    };

    // Fast path: Character and EOF tokens only need a few fields.
    // Skip zeroing ~200 bytes of RustFfiToken for 95%+ of all tokens.
    match token.token_type {
        TokenType::Character | TokenType::EndOfFile => {
            out.token_type = token.token_type as u8;
            out.code_point = token.code_point;
            (out.start_line, out.start_column) = position_to_ffi(handle.tokenizer.position_at(token.start_offset));
            (out.end_line, out.end_column) = position_to_ffi(handle.tokenizer.position_at(token.end_offset));
            return true;
        }
        _ => {}
    }

    *out = RustFfiToken::default();
    out.token_type = token.token_type as u8;

    // NB: Positions are asked for in the order they come in the input, which is the order they are cheapest to find.
    let end_offset = token.end_offset;
    (out.start_line, out.start_column) = position_to_ffi(handle.tokenizer.position_at(token.start_offset));

    // Store string data in handle so pointers stay valid.
    match token.payload {
        TokenPayload::Tag {
            tag_name,
            tag_id: _,
            self_closing,
            had_duplicate_attribute,
            attributes,
        } => {
            out.self_closing = self_closing;
            out.had_duplicate_attribute = had_duplicate_attribute;
            handle.last_tag_name = tag_name;
            out.tag_name = handle.last_tag_name.raw_identity();

            // Move names and values into the handle so the borrowed FFI data remains valid until the next call.
            handle.last_attr_names.clear();
            handle.last_attr_values.clear();
            handle.last_attributes.clear();
            handle.last_attr_names.reserve(attributes.len());
            handle.last_attr_values.reserve(attributes.len());
            handle.last_attributes.reserve(attributes.len());
            for attr in attributes {
                let Attribute {
                    local_name,
                    value,
                    name_start_offset,
                    name_end_offset,
                    value_start_offset,
                    value_end_offset,
                } = attr;
                let (name_start_line, name_start_column) =
                    position_to_ffi(handle.tokenizer.position_at(name_start_offset));
                let (name_end_line, name_end_column) = position_to_ffi(handle.tokenizer.position_at(name_end_offset));
                let (value_start_line, value_start_column) =
                    position_to_ffi(handle.tokenizer.position_at(value_start_offset));
                let (value_end_line, value_end_column) =
                    position_to_ffi(handle.tokenizer.position_at(value_end_offset));
                handle.last_attr_names.push(local_name);
                handle.last_attr_values.push(value.to_utf16());
                let last_idx = handle.last_attr_names.len() - 1;
                let name = &handle.last_attr_names[last_idx];
                let value_code_units = &handle.last_attr_values[last_idx];
                handle.last_attributes.push(RustFfiAttribute {
                    name: name.raw_identity(),
                    value_ptr: value_code_units.as_ptr(),
                    value_len: value_code_units.len(),
                    name_start_line,
                    name_start_column,
                    name_end_line,
                    name_end_column,
                    value_start_line,
                    value_start_column,
                    value_end_line,
                    value_end_column,
                });
            }
            out.attributes_ptr = handle.last_attributes.as_ptr();
            out.attributes_len = handle.last_attributes.len();
        }
        TokenPayload::Comment(data) => {
            handle.last_comment = data.to_utf16();
            out.comment_ptr = handle.last_comment.as_ptr();
            out.comment_len = handle.last_comment.len();
        }
        TokenPayload::Doctype(doctype) => {
            handle.last_doctype_name = doctype.name.to_utf16();
            handle.last_public_id = doctype.public_identifier.to_utf16();
            handle.last_system_id = doctype.system_identifier.to_utf16();
            out.doctype_name_ptr = handle.last_doctype_name.as_ptr();
            out.doctype_name_len = handle.last_doctype_name.len();
            out.public_id_ptr = handle.last_public_id.as_ptr();
            out.public_id_len = handle.last_public_id.len();
            out.system_id_ptr = handle.last_system_id.as_ptr();
            out.system_id_len = handle.last_system_id.len();
            out.force_quirks = doctype.force_quirks;
            out.missing_name = doctype.missing_name;
            out.missing_public_id = doctype.missing_public_identifier;
            out.missing_system_id = doctype.missing_system_identifier;
        }
        TokenPayload::None => {}
    }
    (out.end_line, out.end_column) = position_to_ffi(handle.tokenizer.position_at(end_offset));

    true
}

/// Switch the tokenizer to a new state.
#[unsafe(no_mangle)]
pub extern "C" fn rust_html_tokenizer_switch_state(handle: Option<&mut RustFfiTokenizerHandle>, state: u8) {
    let Some(handle) = handle else {
        return;
    };
    let Some(state) = State::from_ffi(state) else {
        return;
    };
    handle.tokenizer.switch_to(state);
}

/// Insert UTF-16 input at the current insertion point.
#[unsafe(no_mangle)]
pub extern "C" fn rust_html_tokenizer_insert_utf16_input(
    handle: Option<&mut RustFfiTokenizerHandle>,
    input: ak::Span<'_, u16>,
) {
    let Some(handle) = handle else {
        return;
    };
    handle
        .tokenizer
        .insert_input_at_insertion_point(Utf16View::Utf16(input.as_slice()));
}

/// Insert Latin-1 input at the current insertion point.
#[unsafe(no_mangle)]
pub extern "C" fn rust_html_tokenizer_insert_latin1_input(
    handle: Option<&mut RustFfiTokenizerHandle>,
    input: ak::Span<'_, u8>,
) {
    let Some(handle) = handle else {
        return;
    };
    handle
        .tokenizer
        .insert_input_at_insertion_point(Utf16View::Latin1(input.as_slice()));
}

/// Append UTF-16 input to the tokenizer input stream.
#[unsafe(no_mangle)]
pub extern "C" fn rust_html_tokenizer_append_utf16_input(
    handle: Option<&mut RustFfiTokenizerHandle>,
    input: ak::Span<'_, u16>,
) {
    let Some(handle) = handle else {
        return;
    };
    handle.tokenizer.append_input(Utf16View::Utf16(input.as_slice()));
}

/// Append Latin-1 input to the tokenizer input stream.
#[unsafe(no_mangle)]
pub extern "C" fn rust_html_tokenizer_append_latin1_input(
    handle: Option<&mut RustFfiTokenizerHandle>,
    input: ak::Span<'_, u8>,
) {
    let Some(handle) = handle else {
        return;
    };
    handle.tokenizer.append_input(Utf16View::Latin1(input.as_slice()));
}

/// Get the tokenizer input that has not been consumed yet.
#[unsafe(no_mangle)]
pub extern "C" fn rust_html_tokenizer_unparsed_input(
    handle: Option<&mut RustFfiTokenizerHandle>,
    out_ptr: Option<&mut *const u16>,
    out_len: Option<&mut usize>,
) {
    let (Some(handle), Some(out_ptr), Some(out_len)) = (handle, out_ptr, out_len) else {
        return;
    };
    handle.last_unparsed_input = handle.tokenizer.unparsed_input().to_utf16();
    *out_ptr = handle.last_unparsed_input.as_ptr();
    *out_len = handle.last_unparsed_input.len();
}

/// Compact already-tokenized input after the parser has consumed a chunk.
#[unsafe(no_mangle)]
pub extern "C" fn rust_html_tokenizer_parser_did_run(handle: Option<&mut RustFfiTokenizerHandle>) {
    let Some(handle) = handle else {
        return;
    };
    handle.tokenizer.parser_did_run();
}

#[unsafe(no_mangle)]
pub extern "C" fn rust_html_tokenizer_store_insertion_point(handle: Option<&mut RustFfiTokenizerHandle>) {
    let Some(handle) = handle else {
        return;
    };
    handle.tokenizer.store_insertion_point();
}

#[unsafe(no_mangle)]
pub extern "C" fn rust_html_tokenizer_restore_insertion_point(handle: Option<&mut RustFfiTokenizerHandle>) {
    let Some(handle) = handle else {
        return;
    };
    handle.tokenizer.restore_insertion_point();
}

#[unsafe(no_mangle)]
pub extern "C" fn rust_html_tokenizer_update_insertion_point(handle: Option<&mut RustFfiTokenizerHandle>) {
    let Some(handle) = handle else {
        return;
    };
    handle.tokenizer.update_insertion_point();
}

#[unsafe(no_mangle)]
pub extern "C" fn rust_html_tokenizer_undefine_insertion_point(handle: Option<&mut RustFfiTokenizerHandle>) {
    let Some(handle) = handle else {
        return;
    };
    handle.tokenizer.undefine_insertion_point();
}

#[unsafe(no_mangle)]
pub extern "C" fn rust_html_tokenizer_discard_insertion_points(handle: Option<&mut RustFfiTokenizerHandle>) {
    let Some(handle) = handle else {
        return;
    };
    handle.tokenizer.discard_insertion_points();
}

#[unsafe(no_mangle)]
pub extern "C" fn rust_html_tokenizer_is_insertion_point_defined(handle: Option<&mut RustFfiTokenizerHandle>) -> bool {
    let Some(handle) = handle else {
        return false;
    };
    handle.tokenizer.is_insertion_point_defined()
}

#[unsafe(no_mangle)]
pub extern "C" fn rust_html_tokenizer_is_insertion_point_reached(handle: Option<&mut RustFfiTokenizerHandle>) -> bool {
    let Some(handle) = handle else {
        return false;
    };
    handle.tokenizer.is_insertion_point_reached()
}

#[unsafe(no_mangle)]
pub extern "C" fn rust_html_tokenizer_set_input_stream_closed(
    handle: Option<&mut RustFfiTokenizerHandle>,
    closed: bool,
) {
    let Some(handle) = handle else {
        return;
    };
    handle.tokenizer.set_input_stream_closed(closed);
}

#[unsafe(no_mangle)]
pub extern "C" fn rust_html_tokenizer_insert_eof(handle: Option<&mut RustFfiTokenizerHandle>) {
    let Some(handle) = handle else {
        return;
    };
    handle.tokenizer.insert_eof();
}

#[unsafe(no_mangle)]
pub extern "C" fn rust_html_tokenizer_abort(handle: Option<&mut RustFfiTokenizerHandle>) {
    let Some(handle) = handle else {
        return;
    };
    handle.tokenizer.abort();
}

/// Destroy a Rust HTML tokenizer.
///
/// # Safety
/// `handle` must be a valid pointer from `rust_html_tokenizer_create`,
/// and must not be used after this call.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_html_tokenizer_destroy(handle: *mut RustFfiTokenizerHandle) {
    if !handle.is_null() {
        drop(unsafe { Box::from_raw(handle) });
    }
}