use cssparser::{ParseError, Parser, ParserInput, Token};
use lightningcss::traits::Parse;
use lightningcss::values::{calc::Calc, percentage::Percentage};
use crate::nesting::MAX_COLOR_FUNCTION_DEPTH;
const MAX_MATH_FUNCTION_DEPTH: usize = 6;
const COLOR_FUNCTIONS: &[&str] = &[
"rgb",
"rgba",
"hsl",
"hsla",
"hwb",
"lab",
"lch",
"oklab",
"oklch",
"color",
"color-mix",
"light-dark",
"alpha",
];
const MATH_FUNCTIONS: &[&str] = &[
"calc", "min", "max", "clamp", "round", "rem", "mod", "sin", "cos", "tan", "asin", "acos",
"atan", "atan2", "pow", "log", "sqrt", "exp", "hypot", "abs", "sign",
];
const PERCENTAGE_ONLY_PROPERTIES: &[&str] = &[
"font-stretch",
"text-size-adjust",
"-webkit-text-size-adjust",
"-moz-text-size-adjust",
"-ms-text-size-adjust",
"initial-value",
];
const ATAN2_LEVELS: usize = 3;
pub fn style_parse_is_safe(source: &str) -> bool {
if !may_open_checked_function(source) {
return true;
}
let mut input = ParserInput::new(source);
let mut parser = Parser::new(&mut input);
walk(&mut parser, Context::default(), true).is_ok()
}
fn may_open_checked_function(source: &str) -> bool {
let bytes = source.as_bytes();
bytes.contains(&b'\\')
|| bytes.iter().enumerate().any(|(open, &byte)| {
byte == b'(' && {
let start = bytes[..open]
.iter()
.rposition(|&before| !is_name_byte(before))
.map_or(0, |index| index + 1);
let name = &source[start..open];
is_one_of(name, COLOR_FUNCTIONS) || is_one_of(name, MATH_FUNCTIONS)
}
})
}
const fn is_name_byte(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_') || byte >= 0x80
}
#[derive(Clone, Copy, Default)]
struct Context {
colors: usize,
math: usize,
in_math: bool,
number_allowed: bool,
}
impl Context {
fn enter(self, block: Block) -> Self {
Self {
colors: self.colors + usize::from(block.color),
math: self.math + block.math_levels,
in_math: (self.in_math || block.is_math()) && !block.color,
number_allowed: self.number_allowed && !block.rules && !block.legacy_rgb,
}
}
const fn exceeds_caps(self) -> bool {
self.colors > MAX_COLOR_FUNCTION_DEPTH || self.math > MAX_MATH_FUNCTION_DEPTH
}
}
#[derive(Clone, Copy)]
struct Block {
color: bool,
math_levels: usize,
legacy_rgb: bool,
rules: bool,
}
impl Block {
fn of(token: &Token<'_>) -> Option<Self> {
match token {
Token::Function(name) => Some(Self {
color: is_one_of(name, COLOR_FUNCTIONS),
math_levels: if name.eq_ignore_ascii_case("atan2") {
ATAN2_LEVELS
} else {
usize::from(is_one_of(name, MATH_FUNCTIONS))
},
legacy_rgb: is_one_of(name, &["rgb", "rgba"]),
rules: false,
}),
Token::ParenthesisBlock | Token::SquareBracketBlock => Some(Self::bracket(false)),
Token::CurlyBracketBlock => Some(Self::bracket(true)),
_ => None,
}
}
const fn bracket(rules: bool) -> Self {
Self {
color: false,
math_levels: 0,
legacy_rgb: false,
rules,
}
}
const fn is_math(self) -> bool {
self.math_levels > 0
}
}
fn walk<'i>(
parser: &mut Parser<'i, '_>,
outer: Context,
rules: bool,
) -> Result<(), ParseError<'i, ()>> {
let mut context = outer;
let mut property = None;
loop {
let start = parser.position();
let Ok(token) = parser.next() else {
return Ok(());
};
if rules && read_declaration(token, &mut property, &mut context) {
continue;
}
property = None;
let Some(block) = Block::of(token) else {
continue;
};
let inner = context.enter(block);
if inner.exceeds_caps() {
return Err(parser.new_custom_error(()));
}
parser.parse_nested_block(|nested| walk(nested, inner, block.rules))?;
if block.rules {
context.number_allowed = false;
}
if block.is_math()
&& !context.in_math
&& math_function_panics(parser.slice_from(start), context.number_allowed)
{
return Err(parser.new_custom_error(()));
}
}
}
fn read_declaration(token: &Token<'_>, property: &mut Option<bool>, context: &mut Context) -> bool {
match token {
Token::Ident(name) => *property = Some(!is_one_of(name, PERCENTAGE_ONLY_PROPERTIES)),
Token::Colon => context.number_allowed = property.take().unwrap_or(false),
Token::Semicolon => {
context.number_allowed = false;
*property = None;
}
_ => return false,
}
true
}
fn is_one_of(name: &str, names: &[&str]) -> bool {
names.iter().any(|known| name.eq_ignore_ascii_case(known))
}
fn math_function_panics(text: &str, number_allowed: bool) -> bool {
match Calc::<Percentage>::parse_string(text) {
Ok(Calc::Value(_)) | Err(_) => false,
Ok(Calc::Number(_)) => !number_allowed,
Ok(_) => true,
}
}