Skip to content

Truly independent web browser

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

use crate::css::css_enums::{
    keyword, keyword_from_ascii_case_insensitive, keyword_to_counter_style_name_keyword,
    keyword_to_counter_style_system, keyword_to_page_size,
};
use crate::css::css_tokenizer::tokenize_for_parser;
use crate::css::descriptor_metadata::{DescriptorMetadata, DescriptorSyntax, DescriptorValueType, descriptor_metadata};
use crate::css::ffi_support::FfiUtf16View;
use crate::css::parser::arbitrary_substitution::{
    SubstitutionFunctionsPresence, collect_arbitrary_substitution_function_presence, declaration_value_is_valid,
};
use crate::css::parser::component_value::{ComponentValue, consume_a_list_of_component_values};
use crate::css::parser::fonts_parser::parse_font_descriptor;
use crate::css::parser::token_stream::TokenStream;
use crate::css::parser::value_parser::{
    FfiValueParsingContext, FfiValueParsingContextKind, FontDescriptorKind, NumericRange, ParseContext, ParseOutcome,
    is_valid_custom_ident, parse_calculated_numeric_value_with_ranges, parse_css_value, parse_integer_from_stream,
    parse_length_value, parse_percentage_value, string_style_value, unresolved_value, value_list,
};
use crate::css::property_metadata::property_id;
use crate::css::style_compute::FfiLengthResolutionContext;
use crate::css::style_value::CounterStyleSystemPayload;
use crate::css::style_value::StyleValueBox;
use crate::css::style_value::{CssString, RetainedStyleValueData, StyleValueData};
use crate::css::style_value_arc::StyleValueArc;
use crate::css::value_codes::VALUE_TYPE_PERCENTAGE;
use std::ffi::c_void;

#[derive(Clone)]
pub(crate) struct ParsedDescriptor {
    pub id: u8,
    pub value: StyleValueArc,
}

fn non_whitespace(values: &[ComponentValue]) -> smallvec::SmallVec<[&ComponentValue; 8]> {
    values.iter().filter(|value| !value.is_whitespace()).collect()
}

fn single_non_whitespace(values: &[ComponentValue]) -> Option<&ComponentValue> {
    let mut values = values.iter().filter(|value| !value.is_whitespace());
    let value = values.next()?;
    values.next().is_none().then_some(value)
}

fn is_css_wide_keyword(value: &StyleValueData) -> bool {
    matches!(
        value,
        StyleValueData::Keyword {
            keyword: keyword::INHERIT | keyword::INITIAL | keyword::UNSET | keyword::REVERT | keyword::REVERT_LAYER
        }
    )
}

fn parse_keyword(values: &[ComponentValue], expected: &str) -> Option<StyleValueData> {
    let identifier = single_non_whitespace(values)?.ident()?;
    let parsed = keyword_from_ascii_case_insensitive(identifier)?;
    let expected =
        keyword_from_ascii_case_insensitive(&expected.encode_utf16().collect::<smallvec::SmallVec<[u16; 32]>>())?;
    (parsed == expected).then_some(StyleValueData::Keyword { keyword: parsed })
}

fn parse_counter_style_name(_context: &ParseContext, value: &ComponentValue) -> Option<StyleValueData> {
    let identifier = value.ident()?;
    if !is_valid_custom_ident(identifier, &["none"]) {
        return None;
    }
    let name = if keyword_from_ascii_case_insensitive(identifier)
        .is_some_and(|keyword| keyword_to_counter_style_name_keyword(keyword).is_some())
    {
        identifier
            .iter()
            .map(|unit| u16::from(u8::try_from(*unit).unwrap().to_ascii_lowercase()))
            .collect::<Vec<_>>()
    } else {
        identifier.to_vec()
    };
    Some(StyleValueData::CustomIdent {
        custom_ident: CssString::from_utf16(&name),
    })
}

fn parse_symbol(_context: &ParseContext, value: &ComponentValue) -> Option<StyleValueData> {
    if let Some(string) = value.string() {
        return Some(string_style_value(string));
    }
    let identifier = value.ident()?;
    if !is_valid_custom_ident(identifier, &[]) {
        return None;
    }
    Some(StyleValueData::CustomIdent {
        custom_ident: CssString::from_utf16(identifier),
    })
}

fn parse_integer_component(
    context: &ParseContext,
    value: &ComponentValue,
    accepted_range: NumericRange,
) -> Option<(i32, StyleValueData)> {
    let mut stream = TokenStream::new(std::slice::from_ref(value));
    let parsed = parse_integer_from_stream(context, property_id::CUSTOM, &mut stream, accepted_range)?;
    stream.discard_whitespace();
    if !stream.is_empty() {
        return None;
    }
    if matches!(parsed, StyleValueData::Calculated { .. }) {
        super::stylesheet_cache::record_length_resolution_dependency();
    }
    let length_context = context.length_resolution_context;
    Some((resolve_descriptor_integer(&parsed, length_context)?, parsed))
}

/// A descriptor's `<integer>`, with a calculation resolved against the document's lengths when
/// there are some to resolve against.
pub(crate) fn resolve_descriptor_integer(
    value: &StyleValueData,
    length_context: Option<&FfiLengthResolutionContext>,
) -> Option<i32> {
    match value {
        StyleValueData::Integer { value } => Some(*value),
        StyleValueData::Calculated { .. } => length_context
            .and_then(|length_context| crate::css::calc::resolve_calculated_integer_with_context(value, length_context))
            .or_else(|| crate::css::calc::resolve_calculated_integer_without_context(value)),
        _ => None,
    }
}

fn parse_integer_symbol_pair(context: &ParseContext, values: &[ComponentValue]) -> Option<(i32, StyleValueData)> {
    let values = non_whitespace(values);
    if values.len() != 2 {
        return None;
    }
    for (integer_index, symbol_index) in [(0, 1), (1, 0)] {
        if let Some((value, integer)) =
            parse_integer_component(context, values[integer_index], NumericRange::new(0.0, f64::INFINITY))
            && let Some(symbol) = parse_symbol(context, values[symbol_index])
        {
            return Some((value, value_list(vec![integer, symbol], 0, false)));
        }
    }
    None
}

fn parse_counter_style_system(context: &ParseContext, values: &[ComponentValue]) -> Option<StyleValueData> {
    let mut stream = TokenStream::new(values);
    stream.discard_whitespace();
    let identifier = stream.consume_a_token().ident()?;
    let parsed_keyword = keyword_from_ascii_case_insensitive(identifier)?;
    if let Some(system) = keyword_to_counter_style_system(parsed_keyword) {
        stream.discard_whitespace();
        return stream
            .is_empty()
            .then_some(StyleValueData::CounterStyleSystem(StyleValueBox::new(
                CounterStyleSystemPayload {
                    kind: 0,
                    system,
                    first_symbol: RetainedStyleValueData::none(),
                    name: CssString::none(),
                },
            )));
    }
    if parsed_keyword == keyword::FIXED {
        stream.discard_whitespace();
        let first_symbol = if stream.is_empty() {
            RetainedStyleValueData::none()
        } else {
            RetainedStyleValueData::from_owned(parse_integer_from_stream(
                context,
                property_id::CUSTOM,
                &mut stream,
                NumericRange::new(f64::NEG_INFINITY, f64::INFINITY),
            )?)
        };
        stream.discard_whitespace();
        return stream
            .is_empty()
            .then_some(StyleValueData::CounterStyleSystem(StyleValueBox::new(
                CounterStyleSystemPayload {
                    kind: 1,
                    system: 0,
                    first_symbol,
                    name: CssString::none(),
                },
            )));
    }
    if parsed_keyword == keyword::EXTENDS {
        stream.discard_whitespace();
        let StyleValueData::CustomIdent { custom_ident } = parse_counter_style_name(context, stream.consume_a_token())?
        else {
            unreachable!();
        };
        stream.discard_whitespace();
        return stream
            .is_empty()
            .then_some(StyleValueData::CounterStyleSystem(StyleValueBox::new(
                CounterStyleSystemPayload {
                    kind: 2,
                    system: 0,
                    first_symbol: RetainedStyleValueData::none(),
                    name: custom_ident,
                },
            )));
    }
    None
}

fn parse_page_size(context: &ParseContext, values: &[ComponentValue]) -> Option<StyleValueData> {
    if let Some(auto) = parse_keyword(values, "auto") {
        return Some(auto);
    }
    let values = non_whitespace(values);
    if (1..=2).contains(&values.len()) {
        let lengths = values
            .iter()
            .map(|value| {
                parse_length_value(
                    context,
                    property_id::CUSTOM,
                    value,
                    NumericRange::new(0.0, f64::INFINITY),
                )
            })
            .collect::<Option<Vec<_>>>();
        if let Some(mut lengths) = lengths {
            return if lengths.len() == 1 {
                lengths.pop()
            } else {
                Some(value_list(lengths, 0, true))
            };
        }
    }
    let keywords = values
        .iter()
        .map(|value| keyword_from_ascii_case_insensitive(value.ident()?))
        .collect::<Option<Vec<_>>>()?;
    if !(1..=2).contains(&keywords.len()) {
        return None;
    }
    let mut page_size = None;
    let mut orientation = None;
    for keyword in keywords {
        if matches!(keyword, keyword::LANDSCAPE | keyword::PORTRAIT) && orientation.is_none() {
            orientation = Some(keyword);
        } else if keyword_to_page_size(keyword).is_some() && page_size.is_none() {
            page_size = Some(keyword);
        } else {
            return None;
        }
    }
    if page_size.is_some() && orientation == Some(keyword::PORTRAIT) {
        orientation = None;
    }
    let mut result = Vec::new();
    if let Some(keyword) = page_size {
        result.push(StyleValueData::Keyword { keyword });
    }
    if let Some(keyword) = orientation {
        result.push(StyleValueData::Keyword { keyword });
    }
    match result.len() {
        1 => result.pop(),
        2 => Some(value_list(result, 0, true)),
        _ => None,
    }
}

fn parse_counter_style_range(context: &ParseContext, values: &[ComponentValue]) -> Option<StyleValueData> {
    if let Some(auto) = parse_keyword(values, "auto") {
        return Some(auto);
    }
    let mut ranges = Vec::new();
    for range in values.split(ComponentValue::is_comma) {
        let values = non_whitespace(range);
        if values.len() != 2 {
            return None;
        }
        let parse_bound = |value: &ComponentValue, lower: bool| -> Option<(i32, StyleValueData)> {
            if value
                .ident()
                .is_some_and(|ident| keyword_from_ascii_case_insensitive(ident) == Some(keyword::INFINITE))
            {
                return Some((
                    if lower { i32::MIN } else { i32::MAX },
                    StyleValueData::Keyword {
                        keyword: keyword::INFINITE,
                    },
                ));
            }
            parse_integer_component(context, value, NumericRange::new(f64::NEG_INFINITY, f64::INFINITY))
        };
        let (lower, lower_value) = parse_bound(values[0], true)?;
        let (upper, upper_value) = parse_bound(values[1], false)?;
        if lower > upper {
            return None;
        }
        ranges.push(value_list(vec![lower_value, upper_value], 0, false));
    }
    (!ranges.is_empty()).then(|| value_list(ranges, 1, true))
}

fn parse_value_type(
    context: &ParseContext,
    value_type: DescriptorValueType,
    values: &[ComponentValue],
    source: &[u16],
) -> Option<StyleValueData> {
    match value_type {
        DescriptorValueType::FamilyName => {
            match parse_font_descriptor(context, FontDescriptorKind::FamilyName, values) {
                ParseOutcome::Parsed(value) => Some(StyleValueArc::unwrap_or_clone(value)),
                _ => None,
            }
        }
        DescriptorValueType::FontSrcList => {
            match parse_font_descriptor(context, FontDescriptorKind::SourceList, values) {
                ParseOutcome::Parsed(value) => Some(StyleValueArc::unwrap_or_clone(value)),
                _ => None,
            }
        }
        DescriptorValueType::UnicodeRangeTokens => {
            match parse_font_descriptor(context, FontDescriptorKind::UnicodeRangeList, values) {
                ParseOutcome::Parsed(value) => Some(StyleValueArc::unwrap_or_clone(value)),
                _ => None,
            }
        }
        DescriptorValueType::Length => parse_length_value(
            context,
            property_id::CUSTOM,
            single_non_whitespace(values)?,
            NumericRange::new(f64::NEG_INFINITY, f64::INFINITY),
        ),
        DescriptorValueType::PositivePercentage => {
            let value = single_non_whitespace(values)?;
            let range = NumericRange::new(0.0, f64::INFINITY);
            if let Some((name, arguments)) = value.function() {
                parse_calculated_numeric_value_with_ranges(
                    context,
                    property_id::CUSTOM,
                    VALUE_TYPE_PERCENTAGE,
                    None,
                    range,
                    name,
                    arguments,
                )
            } else {
                parse_percentage_value(value, range)
            }
        }
        DescriptorValueType::String => Some(string_style_value(single_non_whitespace(values)?.string()?)),
        DescriptorValueType::Symbol => parse_symbol(context, single_non_whitespace(values)?),
        DescriptorValueType::Symbols => {
            let symbols = non_whitespace(values)
                .into_iter()
                .map(|value| parse_symbol(context, value))
                .collect::<Option<Vec<_>>>()?;
            (!symbols.is_empty()).then(|| value_list(symbols, 0, false))
        }
        DescriptorValueType::CounterStyleName => parse_counter_style_name(context, single_non_whitespace(values)?),
        DescriptorValueType::CounterStyleNegative => {
            let values = non_whitespace(values);
            if !(1..=2).contains(&values.len()) {
                return None;
            }
            let collapsible = values.len() == 1;
            Some(value_list(
                values
                    .into_iter()
                    .map(|value| parse_symbol(context, value))
                    .collect::<Option<Vec<_>>>()?,
                0,
                collapsible,
            ))
        }
        DescriptorValueType::CounterStylePad => {
            let (_, pair) = parse_integer_symbol_pair(context, values)?;
            Some(pair)
        }
        DescriptorValueType::CounterStyleAdditiveSymbols => {
            let mut previous = i32::MAX;
            let mut tuples = Vec::new();
            for tuple in values.split(ComponentValue::is_comma) {
                let (integer, pair) = parse_integer_symbol_pair(context, tuple)?;
                if integer >= previous {
                    return None;
                }
                previous = integer;
                tuples.push(pair);
            }
            (!tuples.is_empty()).then(|| value_list(tuples, 1, true))
        }
        DescriptorValueType::CounterStyleSystem => parse_counter_style_system(context, values),
        DescriptorValueType::CounterStyleRange => parse_counter_style_range(context, values),
        DescriptorValueType::CropOrCross => {
            let values = non_whitespace(values);
            if !(1..=2).contains(&values.len()) {
                return None;
            }
            let keywords = values
                .into_iter()
                .map(|value| keyword_from_ascii_case_insensitive(value.ident()?))
                .collect::<Option<Vec<_>>>()?;
            if keywords
                .iter()
                .any(|value| !matches!(*value, keyword::CROP | keyword::CROSS))
                || keywords.len() == 2 && keywords[0] == keywords[1]
            {
                return None;
            }
            if keywords.len() == 1 {
                Some(StyleValueData::Keyword { keyword: keywords[0] })
            } else {
                Some(value_list(
                    vec![
                        StyleValueData::Keyword { keyword: keyword::CROP },
                        StyleValueData::Keyword {
                            keyword: keyword::CROSS,
                        },
                    ],
                    0,
                    true,
                ))
            }
        }
        DescriptorValueType::FontWeightAbsolutePair => {
            let values = non_whitespace(values);
            if !(1..=2).contains(&values.len()) {
                return None;
            }
            let parsed = values
                .iter()
                .map(
                    |value| match parse_css_value(context, property_id::FONT_WEIGHT, std::slice::from_ref(value)) {
                        ParseOutcome::Parsed(value)
                            if !is_css_wide_keyword(&value)
                                && !matches!(
                                    &*value,
                                    StyleValueData::Keyword {
                                        keyword: keyword::BOLDER | keyword::LIGHTER
                                    }
                                ) =>
                        {
                            Some(StyleValueArc::unwrap_or_clone(value))
                        }
                        _ => None,
                    },
                )
                .collect::<Option<Vec<_>>>()?;
            Some(value_list(parsed, 0, false))
        }
        DescriptorValueType::OptionalDeclarationValue => {
            if !values.is_empty() && !declaration_value_is_valid(values) {
                return None;
            }
            Some(unresolved_value(
                source,
                values,
                SubstitutionFunctionsPresence::default(),
            ))
        }
        DescriptorValueType::PageSize => parse_page_size(context, values),
    }
}

fn parse_with_metadata(
    context: &ParseContext,
    metadata: &DescriptorMetadata,
    values: &[ComponentValue],
    source: &[u16],
) -> Option<StyleValueData> {
    if !metadata.allow_css_wide_keywords
        && single_non_whitespace(values)
            .and_then(ComponentValue::ident)
            .and_then(keyword_from_ascii_case_insensitive)
            .is_some_and(|keyword| is_css_wide_keyword(&StyleValueData::Keyword { keyword }))
    {
        return None;
    }
    for syntax in metadata.syntax {
        let parsed = match syntax {
            DescriptorSyntax::Keyword(keyword) => parse_keyword(values, keyword),
            DescriptorSyntax::Property(property) => match parse_css_value(context, *property, values) {
                ParseOutcome::Parsed(value) if metadata.allow_css_wide_keywords || !is_css_wide_keyword(&value) => {
                    Some(StyleValueArc::unwrap_or_clone(value))
                }
                _ => None,
            },
            DescriptorSyntax::ValueType(value_type) => parse_value_type(context, *value_type, values, source),
        };
        if parsed.is_some() {
            return parsed;
        }
    }
    None
}

pub(crate) fn parse_descriptor(
    context: &ParseContext,
    at_rule: u8,
    name: &[u16],
    values: &[ComponentValue],
    source: &[u16],
) -> Option<ParsedDescriptor> {
    let metadata = descriptor_metadata(at_rule, name)?;
    let inherited_contexts = context.value_contexts.as_slice();
    let mut value_contexts = Vec::with_capacity(inherited_contexts.len() + 1);
    value_contexts.extend_from_slice(inherited_contexts);
    value_contexts.push(FfiValueParsingContext {
        kind: FfiValueParsingContextKind::Descriptor,
        value: u16::from(at_rule),
        secondary_value: 0,
        name: FfiUtf16View::default(),
    });
    let mut descriptor_context = *context;
    descriptor_context.value_contexts = ak::Span::new(&value_contexts);
    let mut presence = SubstitutionFunctionsPresence::default();
    collect_arbitrary_substitution_function_presence(values, &mut presence).ok()?;
    let value = if presence.has_any() {
        if !metadata.allow_arbitrary_substitution_functions {
            return None;
        }
        unresolved_value(source, values, presence)
    } else {
        parse_with_metadata(&descriptor_context, &metadata, values, source)?
    };
    Some(ParsedDescriptor {
        id: metadata.id,
        value: StyleValueArc::new(value),
    })
}

/// Parses one descriptor value and returns retained Rust style-value data.
#[unsafe(no_mangle)]
pub extern "C" fn rust_parse_css_descriptor(
    context: Option<&ParseContext>,
    at_rule: u8,
    name: FfiUtf16View,
    source: FfiUtf16View,
) -> *const c_void {
    let Some(context) = context else {
        return std::ptr::null();
    };
    let Some(name) = name.units() else {
        return std::ptr::null();
    };
    let Some(source) = source.units() else {
        return std::ptr::null();
    };
    let Ok(values) = consume_a_list_of_component_values(tokenize_for_parser(source)) else {
        return std::ptr::null();
    };
    let mut name_units = Vec::with_capacity(name.len());
    name.append_to(&mut name_units);
    let mut source_units = Vec::with_capacity(source.len());
    source.append_to(&mut source_units);
    parse_descriptor(context, at_rule, &name_units, &values, &source_units)
        .map(|descriptor| StyleValueArc::into_raw(descriptor.value).cast::<c_void>())
        .unwrap_or(std::ptr::null())
}

/// The value of the descriptor of the at-rule that the text parses to, in an empty context.
pub(crate) fn parse_descriptor_text(at_rule: u8, name: &[u16], source: &[u16]) -> Option<StyleValueArc> {
    let values = consume_a_list_of_component_values(tokenize_for_parser(source)).ok()?;
    parse_descriptor(&ParseContext::default(), at_rule, name, &values, source).map(|descriptor| descriptor.value)
}

#[cfg(test)]
mod tests {
    use super::{consume_a_list_of_component_values, parse_descriptor, tokenize_for_parser};
    use crate::css::parser::value_parser::ParseContext;
    use crate::css::style_value::StyleValueData;
    use crate::css::style_value_arc::StyleValueArc;

    fn context() -> ParseContext<'static> {
        ParseContext::default()
    }

    fn parse(at_rule: u8, name: &str, source: &str) -> Option<StyleValueData> {
        let values = consume_a_list_of_component_values(tokenize_for_parser(source.as_bytes())).unwrap();
        let source = source.encode_utf16().collect::<Vec<_>>();
        StyleValueArc::into_inner(
            parse_descriptor(
                &context(),
                at_rule,
                &name.encode_utf16().collect::<Vec<_>>(),
                &values,
                &source,
            )?
            .value,
        )
    }

    #[test]
    fn parses_representative_descriptors() {
        assert!(matches!(
            parse(0, "font-display", "swap"),
            Some(StyleValueData::Keyword { .. })
        ));
        assert!(matches!(
            parse(0, "font-weight", "bold"),
            Some(StyleValueData::ValueList { .. })
        ));
        assert!(matches!(
            parse(0, "font-width", "condensed"),
            Some(StyleValueData::Keyword { .. })
        ));
        assert!(matches!(
            parse(1, "marks", "cross crop"),
            Some(StyleValueData::ValueList { .. })
        ));
        assert!(matches!(
            parse(1, "size", "portrait"),
            Some(StyleValueData::Keyword { .. })
        ));
        assert!(matches!(
            parse(2, "inherits", "false"),
            Some(StyleValueData::Keyword { .. })
        ));
        assert!(matches!(
            parse(3, "pad", "2 '0'"),
            Some(StyleValueData::ValueList { .. })
        ));
        assert!(matches!(
            parse(3, "symbols", "'X' 'Y'"),
            Some(StyleValueData::ValueList { .. })
        ));
        assert!(matches!(
            parse(3, "negative", "'X' 'Y'"),
            Some(StyleValueData::ValueList { .. })
        ));
        assert!(parse(3, "additive-symbols", "1 a, 2 b").is_none());
        assert!(matches!(
            parse(3, "pad", "calc(1 + 2) '0'"),
            Some(StyleValueData::ValueList { .. })
        ));
        assert!(matches!(
            parse(3, "range", "calc(calc(2 + 1) * 2) infinite"),
            Some(StyleValueData::ValueList { .. })
        ));
        assert!(parse(3, "pad", "calc(1px + 2px) '0'").is_none());
        assert!(parse(0, "font-display", "var(--display)").is_none());
        assert!(parse(0, "font-weight", "calc(max(0 * sibling-index(), 400))").is_none());
    }
}