#[derive(Debug, Default, PartialEq, Eq)]
pub(super) struct KeyframeHints {
pub(super) opaque_reference: bool,
pub(super) possible_names: Vec<String>,
pub(super) animation_variables: Vec<String>,
pub(super) argument_variables: Vec<String>,
pub(super) assignments: Vec<(String, Option<Vec<String>>)>,
}
pub(super) fn preprocessor_keyframe_hints(source: &str) -> KeyframeHints {
let mut hints = KeyframeHints::default();
let mut scopes: Vec<Vec<String>> = Vec::new();
let source = blank_comments(source, BlockComments::Blank);
for (statement, terminator) in statements(&source) {
let statement = statement.trim();
match terminator {
b'{' => scopes.push(mixin_parameters(statement, &mut hints)),
b'}' => {
scan_declaration(statement, &scopes, &mut hints);
scopes.pop();
}
_ => scan_declaration(statement, &scopes, &mut hints),
}
}
hints.possible_names.sort_unstable();
hints.possible_names.dedup();
hints
}
fn scan_declaration(statement: &str, scopes: &[Vec<String>], hints: &mut KeyframeHints) {
if let Some(rest) = statement.strip_prefix("@include") {
push_call_arguments(rest, hints);
} else if is_less_mixin_call(statement) {
push_call_arguments(statement, hints);
} else if let Some((name, value)) = variable_assignment(statement) {
let names = (!is_dynamic_value(value) && !value.contains('(')).then(|| {
let mut names = Vec::new();
push_identifiers(value, &mut names);
names
});
hints.assignments.push((name.to_owned(), names));
} else if let Some(value) = animation_value(statement) {
if value.contains("#{") || value.contains("@{") {
hints.opaque_reference = true;
return;
}
push_identifiers(value, &mut hints.possible_names);
for variable in variables(value) {
if !scopes.iter().flatten().any(|param| *param == variable) {
hints.animation_variables.push(variable.to_owned());
}
}
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum BlockComments {
Blank,
Keep,
}
pub(super) fn blank_comments(source: &str, block: BlockComments) -> String {
let mut bytes = source.as_bytes().to_vec();
let mut i = 0;
while i < bytes.len() {
let end = match bytes[i] {
quote @ (b'"' | b'\'') => {
i = skip_string(&bytes, i + 1, quote);
continue;
}
b'/' if bytes.get(i + 1) == Some(&b'*') => {
let end = skip_block_comment(&bytes, i + 2);
if block == BlockComments::Keep {
i = end;
continue;
}
end
}
b'/' if bytes.get(i + 1) == Some(&b'/') && (i == 0 || bytes[i - 1] != b':') => {
line_end(&bytes, i)
}
b'(' if opens_url(&bytes, i) => {
i = skip_unquoted_url(&bytes, i + 1);
continue;
}
_ => {
i += 1;
continue;
}
};
for byte in &mut bytes[i..end] {
if *byte != b'\n' {
*byte = b' ';
}
}
i = end;
}
String::from_utf8(bytes).unwrap_or_else(|_| source.to_owned())
}
fn statements(source: &str) -> Vec<(&str, u8)> {
let bytes = source.as_bytes();
let mut out = Vec::new();
let mut start = 0;
let mut depth = 0usize;
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'#' | b'@' if bytes.get(i + 1) == Some(&b'{') => {
i = skip_past(bytes, i + 2, b'}');
}
quote @ (b'"' | b'\'') => i = skip_string(bytes, i + 1, quote),
b'(' => {
depth += 1;
i += 1;
}
b')' => {
depth = depth.saturating_sub(1);
i += 1;
}
b';' if depth > 0 => i += 1,
terminator @ (b';' | b'{' | b'}') => {
out.push((&source[start..i], terminator));
depth = 0;
i += 1;
start = i;
}
_ => i += 1,
}
}
out.push((&source[start..], b';'));
out
}
fn skip_past(bytes: &[u8], from: usize, end: u8) -> usize {
bytes[from.min(bytes.len())..]
.iter()
.position(|&b| b == end)
.map_or(bytes.len(), |offset| from + offset + 1)
}
fn skip_string(bytes: &[u8], mut i: usize, quote: u8) -> usize {
while i < bytes.len() {
match bytes[i] {
b'\\' => i += 2,
b'\n' => return i,
b if b == quote => return i + 1,
_ => i += 1,
}
}
bytes.len()
}
fn line_end(bytes: &[u8], from: usize) -> usize {
bytes[from..]
.iter()
.position(|&b| b == b'\n')
.map_or(bytes.len(), |offset| from + offset)
}
fn opens_url(bytes: &[u8], paren: usize) -> bool {
paren >= 3
&& bytes[paren - 3..paren].eq_ignore_ascii_case(b"url")
&& (paren == 3
|| !matches!(bytes[paren - 4], b'-' | b'_' | b'$' | b'@')
&& !bytes[paren - 4].is_ascii_alphanumeric())
}
fn skip_unquoted_url(bytes: &[u8], from: usize) -> usize {
let body = from
+ bytes[from..]
.iter()
.take_while(|b| matches!(b, b' ' | b'\t'))
.count();
if matches!(bytes.get(body), Some(b'"' | b'\'')) {
return body;
}
bytes[body..]
.iter()
.position(|&b| matches!(b, b')' | b'\n' | b'"' | b'\''))
.map_or(bytes.len(), |offset| body + offset)
}
fn skip_block_comment(bytes: &[u8], from: usize) -> usize {
bytes[from.min(bytes.len())..]
.windows(2)
.position(|pair| pair == b"*/")
.map_or(bytes.len(), |offset| from + offset + 2)
}
fn mixin_parameters(prelude: &str, hints: &mut KeyframeHints) -> Vec<String> {
let less = is_less_mixin_head(prelude);
if !less && !prelude.starts_with("@mixin") {
return Vec::new();
}
let Some(open) = prelude.find('(') else {
return Vec::new();
};
let list = prelude[open + 1..]
.rfind(')')
.map_or(&prelude[open + 1..], |close| {
&prelude[open + 1..open + 1 + close]
});
let mut parameters = Vec::new();
for parameter in list.split([',', ';']) {
let (name, default) = parameter.split_once(':').unwrap_or((parameter, ""));
parameters.extend(variables(name).map(str::to_owned));
push_arguments(default, hints);
}
if less {
parameters.push("@arguments".to_owned());
}
parameters
}
fn is_less_mixin_call(statement: &str) -> bool {
is_less_mixin_head(statement)
}
fn is_less_mixin_head(statement: &str) -> bool {
let mut chars = statement.chars();
let starts_as_mixin = matches!(chars.next(), Some('.' | '#'))
&& chars
.next()
.is_some_and(|c| c.is_ascii_alphabetic() || matches!(c, '_' | '-'));
starts_as_mixin
&& statement
.split_once('(')
.is_some_and(|(head, _)| !head.contains(':'))
}
fn variable_assignment(statement: &str) -> Option<(&str, &str)> {
let (name, value) = statement.split_once(':')?;
let name = name.trim();
let sigil = name.bytes().next()?;
let ident = &name[1..];
let is_variable =
matches!(sigil, b'$' | b'@') && !ident.is_empty() && ident.bytes().all(is_ident_continue);
is_variable.then_some((name, value))
}
fn animation_value(statement: &str) -> Option<&str> {
let (property, value) = statement.split_once(':')?;
let property = property.trim().to_ascii_lowercase();
let property = ["-webkit-", "-moz-", "-o-", "-ms-"]
.iter()
.find_map(|prefix| property.strip_prefix(prefix))
.unwrap_or(&property);
matches!(property, "animation" | "animation-name").then_some(value)
}
fn is_dynamic_value(value: &str) -> bool {
value.contains("#{") || value.contains("@{") || variables(value).next().is_some()
}
fn variables(text: &str) -> impl Iterator<Item = &str> {
let bytes = text.as_bytes();
bytes.iter().enumerate().filter_map(move |(i, &b)| {
if !matches!(b, b'$' | b'@') {
return None;
}
let first = *bytes.get(i + 1)?;
if !(first.is_ascii_alphabetic() || first == b'_' || first == b'-') {
return None;
}
let end = bytes[i + 1..]
.iter()
.position(|c| !is_ident_continue(*c))
.map_or(bytes.len(), |offset| i + 1 + offset);
Some(&text[i..end])
})
}
fn push_call_arguments(call: &str, hints: &mut KeyframeHints) {
let Some(open) = call.find('(') else {
return;
};
let arguments = call[open + 1..]
.rfind(')')
.map_or(&call[open + 1..], |close| &call[open + 1..open + 1 + close]);
push_arguments(arguments, hints);
}
fn push_arguments(arguments: &str, hints: &mut KeyframeHints) {
if arguments.contains("#{") || arguments.contains("@{") {
hints.opaque_reference = true;
}
push_identifiers(arguments, &mut hints.possible_names);
hints
.argument_variables
.extend(variables(arguments).map(str::to_owned));
}
fn push_identifiers(text: &str, into: &mut Vec<String>) {
let bytes = text.as_bytes();
let mut i = 0;
while i < bytes.len() {
let b = bytes[i];
if is_ident_continue(b) {
let start = i;
while i < bytes.len() && is_ident_continue(bytes[i]) {
i += 1;
}
let preceded_by_sigil =
start > 0 && matches!(bytes[start - 1], b'$' | b'@' | b'.' | b'!');
let word = &text[start..i];
let starts_as_ident = word
.bytes()
.find(|c| *c != b'-')
.is_some_and(|c| c.is_ascii_alphabetic() || c == b'_');
if !preceded_by_sigil && starts_as_ident {
into.push(word.to_owned());
}
} else {
i += 1;
}
}
}
fn is_ident_continue(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-')
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn interpolation_in_animation_value_is_opaque() {
for source in [
".b { -webkit-animation-name: #{$prefix}-spin; }",
".b { animation-name: ~\"@{prefix}-spin\"; }",
"@mixin m($name) { animation: #{$name}-in 1s; }",
] {
assert!(
preprocessor_keyframe_hints(source).opaque_reference,
"{source}"
);
}
}
#[test]
fn free_variable_in_animation_value_is_recorded() {
let hints =
preprocessor_keyframe_hints(".b { animation: $fade 2s; }\n.c { animation: @name 1s; }");
assert!(!hints.opaque_reference);
assert_eq!(hints.animation_variables, vec!["$fade", "@name"]);
}
#[test]
fn mixin_parameter_in_animation_value_is_not_recorded() {
for source in [
"@mixin animate($name, $d: 1s) { animation: $name $d; }\n.a { @include animate(spin); }",
".m(@a; @b) { animation: @a 1s; }\n.x { .m(spin; 2s); }",
".m(@a) { animation: @arguments; }",
"@mixin outer($n) { .x { animation: $n 1s; } }",
] {
let hints = preprocessor_keyframe_hints(source);
assert!(!hints.opaque_reference, "{source}");
assert!(hints.animation_variables.is_empty(), "{source}: {hints:?}");
}
}
#[test]
fn mixin_parameter_does_not_leak_out_of_its_scope() {
let source = "@mixin m($name) { animation: $name 1s; }\n.a { animation: $name 2s; }";
let hints = preprocessor_keyframe_hints(source);
assert_eq!(hints.animation_variables, vec!["$name"]);
}
#[test]
fn literal_assignment_is_recorded() {
let source = "$fade: fade-in !default;\n@pulse: pulse;\n$other: $fade;\n$id: unique-id();\n.a { animation: $fade 1s; }";
let hints = preprocessor_keyframe_hints(source);
assert_eq!(
hints.assignments,
vec![
("$fade".to_owned(), Some(vec!["fade-in".to_owned()])),
("@pulse".to_owned(), Some(vec!["pulse".to_owned()])),
("$other".to_owned(), None),
("$id".to_owned(), None),
]
);
}
#[test]
fn literal_animation_value_gives_possible_names() {
let source =
"%pulse { animation-name: pulsate; }\n.a { animation: spin 1s linear; color: $red; }";
let hints = preprocessor_keyframe_hints(source);
assert!(!hints.opaque_reference);
assert_eq!(hints.possible_names, vec!["linear", "pulsate", "spin"]);
}
#[test]
fn mixin_call_arguments_are_collected() {
let source = ".a { @include animate(spin, $speed, 2s); }\n.b { .pulse(fade-in 1s); }\n.c:not(.d) { color: red; }\n";
let hints = preprocessor_keyframe_hints(source);
assert!(!hints.opaque_reference);
assert_eq!(hints.possible_names, vec!["fade-in", "spin"]);
assert_eq!(hints.argument_variables, vec!["$speed"]);
}
#[test]
fn less_named_and_semicolon_arguments_are_collected() {
let source = ".x { .m(@b: spin); }\n.y { .m(pulse; 2s); }\n.z { #ns.m(@a: fade); }";
let hints = preprocessor_keyframe_hints(source);
assert_eq!(hints.possible_names, vec!["fade", "pulse", "spin"]);
}
#[test]
fn interpolation_braces_do_not_end_a_statement() {
let source = ".a { animation: #{$name} 1s; }\n.b { @include x(spin); }";
let hints = preprocessor_keyframe_hints(source);
assert!(hints.opaque_reference);
assert_eq!(hints.possible_names, vec!["spin"]);
}
#[test]
fn comment_above_a_statement_does_not_hide_it() {
for comment in ["// note", "/* note */"] {
let source = format!(
".a {{\n {comment}\n animation: #{{$p}}-go 1s;\n}}\n\
.b {{\n {comment}\n @include an(spin);\n}}\n\
{comment}\n$fade: fade-in;\n"
);
let hints = preprocessor_keyframe_hints(&source);
assert!(hints.opaque_reference, "{source}");
assert_eq!(hints.possible_names, vec!["spin"], "{source}");
assert_eq!(
hints.assignments,
vec![("$fade".to_owned(), Some(vec!["fade-in".to_owned()]))],
"{source}"
);
}
}
#[test]
fn protocol_relative_url_is_no_comment() {
let source = ".a { background: url(//cdn.example/a.png); animation: spin 1s; }";
let hints = preprocessor_keyframe_hints(source);
assert_eq!(hints.possible_names, vec!["spin"]);
}
#[test]
fn mixin_parameter_defaults_count_as_arguments() {
let hints = preprocessor_keyframe_hints(
"@mixin an($n: spin, $d: $def) { animation: $n $d; }\n.m(@a: pulse) { animation: @a; }",
);
assert!(hints.animation_variables.is_empty(), "{hints:?}");
assert_eq!(hints.possible_names, vec!["pulse", "spin"]);
assert_eq!(hints.argument_variables, vec!["$def"]);
}
#[test]
fn interpolated_mixin_argument_is_opaque() {
let hints = preprocessor_keyframe_hints(".a { @include an(#{$p}-spin); }");
assert!(hints.opaque_reference);
}
#[test]
fn comments_hide_their_content() {
let source = "// animation: $x;\n/* @include y(spin); */\n.a { color: red; }";
assert_eq!(
preprocessor_keyframe_hints(source),
KeyframeHints::default()
);
}
}