rust_css_parser/ast/features/
inlinecssvariables.rs1use super::r#type::FeatureWalkMode;
4use super::{FeatureResult, MinifyFeature, SharedFeature};
5use crate::ast::arena::{AstArena, StrOrId, TokenField, TokenValue};
6use crate::ast::minify::{split_rule, MinifyContext};
7use crate::ast::mixins::utils::is_in_template;
8use crate::ast::types::{EnumAstNodeStatus, EnumToken};
9use crate::ast::walk::{ValueWalker, WalkerValueOptions};
10use crate::options::{ConvertColor, ParserOptions};
11use crate::printer::render::render_value;
12use crate::syntax::constants::MATH_FUNCS;
13use std::cell::RefCell;
14use std::rc::Rc;
15
16pub struct VariableScopeInfo {
18 pub replaceable: bool,
19 pub parent: u32,
21 pub node: u32,
22 pub values: Vec<u32>,
24}
25
26pub type VariableScope = Rc<RefCell<crate::parser::declaration::JsMap<VariableScopeInfo>>>;
28
29fn inline_expression(arena: &AstArena, token: u32) -> Vec<u32> {
31 if arena.data_types.get(token) != EnumToken::BinaryExpressionTokenType {
32 return vec![token];
33 }
34 let mut chi = inline_expression(arena, arena.field(token, TokenField::L));
35 chi.push(arena.create_token(arena.numeric_value.get(token) as u8, TokenValue::None, None));
36 chi.extend(inline_expression(arena, arena.field(token, TokenField::R)));
37 vec![arena.create_list(EnumToken::ParensTokenType, Some(&chi))]
38}
39
40fn replace(arena: &AstArena, node: u32, variable_scope: &VariableScope) {
41 let mut walker = ValueWalker::of_node(arena, node, WalkerValueOptions::default(), false);
42 while let Some(value) = walker.next(arena) {
43 let parent_value = match arena.get_value_parent(value) {
45 0 => node,
46 p => p,
47 };
48 if arena.data_types.get(value) == EnumToken::BinaryExpressionTokenType && parent_value != node && arena.parents.get(value) == parent_value {
49 arena.replace_token(value, &inline_expression(arena, value));
50 }
51 }
52 let mut walker = ValueWalker::of_node(arena, node, WalkerValueOptions::default(), false);
53 while let Some(value) = walker.next(arena) {
54 let typ = arena.data_types.get(value);
55 if typ == EnumToken::MathFunctionTokenType || (typ == EnumToken::WildCardFunctionTokenType && arena.string_equals(arena.string_value.get(value), "var")) {
56 let first = arena.first_token.get(value);
57 if first != 0 && arena.next_sibling.get(first) == 0 && arena.data_types.get(first) == EnumToken::DashedIdenTokenType {
58 let scope = variable_scope.borrow();
59 let info = arena.with_string(arena.string_value.get(first), |name| scope.get(name).map(|i| (i.replaceable, i.node)));
60 if let Some((true, declaration)) = info {
62 if arena.name.get(declaration) != 0 && arena.parents.get(value) != 0 {
63 let tokens: Vec<u32> = arena.tokens(declaration).into_iter().map(|t| arena.clone_node_deep(t, true, None)).collect();
64 drop(scope);
65 arena.replace_token(value, &tokens);
66 }
67 }
68 }
69 }
70 }
71}
72
73pub struct InlineCssVariablesFeature;
74
75const ACCEPT: [u8; 2] = [EnumToken::RuleNodeType, EnumToken::AtRuleNodeType];
76
77impl InlineCssVariablesFeature {
78 pub fn register(options: &ParserOptions, features: &mut Vec<SharedFeature>) {
79 if options.inline_css_variables == Some(true) {
80 features.push(Rc::new(RefCell::new(InlineCssVariablesFeature)));
81 }
82 }
83}
84
85impl MinifyFeature for InlineCssVariablesFeature {
86 fn accept(&self) -> Option<&[u8]> {
87 Some(&ACCEPT)
88 }
89
90 fn ordering(&self) -> i32 {
91 2
92 }
93
94 fn process_mode(&self) -> u32 {
95 FeatureWalkMode::Post
96 }
97
98 fn run(&mut self, arena: &AstArena, ast: u32, _options: &ParserOptions, parent: u32, context: &mut MinifyContext, _mode: u32) -> FeatureResult {
99 if arena.flags.get(ast) & EnumAstNodeStatus::HasChildren == 0 || is_in_template(arena, ast) {
101 return FeatureResult::None;
102 }
103 let variable_scope: VariableScope = context.get_or_insert_with("variableScope", VariableScope::default).clone();
104 let is_root = arena.data_types.get(parent) == EnumToken::StyleSheetNodeType && arena.data_types.get(ast) == EnumToken::RuleNodeType && {
106 let raw = arena.raw.borrow().get(&ast).cloned().unwrap_or_else(|| std::rc::Rc::new(crate::ast::arena::RawSelector::from(split_rule(&arena.resolve_string(arena.name.get(ast))))));
107 raw.iter().any(|segment| segment.iter().any(|s| s == ":root" || s == "html"))
108 };
109 let mut node = arena.first_child.get(ast);
110 while node != 0 {
111 if arena.data_types.get(node) == EnumToken::DeclarationNodeType {
112 if arena.string_starts_with(arena.name.get(node), "--") {
113 let name = arena.resolve_string(arena.name.get(node));
115 let values = arena.tokens(node).into_iter().map(|t| arena.clone_node_deep(t, true, None)).collect();
116 variable_scope.borrow_mut().set(name, VariableScopeInfo { replaceable: is_root, parent: ast, node, values });
117 let mut recursive = false;
118 let mut walker = ValueWalker::of_node(arena, node, WalkerValueOptions::default(), false);
119 while let Some(value) = walker.next(arena) {
120 let typ = arena.data_types.get(value);
121 if typ == EnumToken::MathFunctionTokenDefType
122 || (typ == EnumToken::WildCardFunctionTokenType
123 && arena.with_string(arena.string_value.get(value), |v| MATH_FUNCS.contains(&v) || v == "var"))
124 {
125 recursive = true;
126 break;
127 }
128 }
129 if recursive {
130 replace(arena, node, &variable_scope);
131 }
132 } else {
133 replace(arena, node, &variable_scope);
134 }
135 }
136 node = arena.next_sibling.get(node);
137 }
138 FeatureResult::None
139 }
140
141 fn has_cleanup(&self) -> bool {
142 true
143 }
144
145 fn cleanup(&mut self, arena: &AstArena, _ast: u32, _options: &ParserOptions, context: &mut MinifyContext, _mode: u32) {
146 let Some(variable_scope) = context.get_mut::<VariableScope>("variableScope").cloned() else {
147 return;
148 };
149 thread_local! {
150 static OPTIONS: ParserOptions = ParserOptions { convert_color: Some(ConvertColor::Bool(false)), ..Default::default() };
151 }
152 for info in variable_scope.borrow().values() {
153 if info.replaceable && arena.parents.get(info.node) == info.parent {
155 let mut text = format!("/* {}: ", arena.resolve_string(arena.name.get(info.node)));
156 OPTIONS.with(|o| {
157 for &t in &info.values {
158 text.push_str(&render_value(arena, t, o));
159 }
160 });
161 text.push_str(" */");
162 let comment = arena.create_comment(EnumToken::CommentTokenType, StrOrId::Str(&text));
163 arena.replace_child(info.node, &[comment]);
164 arena.detach(info.node);
165 }
166 }
167 }
168}