Skip to main content

rust_css_parser/ast/features/
if_.rs

1//! Port of `src/ast/features/if.ts`: `if()` conditions expanded into declarations and at-rules.
2
3use super::r#type::FeatureWalkMode;
4use super::{FeatureResult, MinifyFeature, SharedFeature};
5use crate::ast::arena::{Arena, AstArena, StrOrId, TokenField};
6use crate::ast::minify::MinifyContext;
7use crate::ast::types::EnumToken;
8use crate::options::{ConvertColor, ParserOptions};
9use crate::parser::utils::eq::eq_token;
10use crate::printer::render::render_value;
11use crate::validation::match_::trim_array;
12use std::cell::RefCell;
13use crate::utils::fx::HashMap;
14use std::rc::Rc;
15
16/// true if the token is an if() function or an if condition
17fn is_if_token(arena: &Arena, value: u32) -> bool {
18    arena.data_types.get(value) == EnumToken::IfConditionTokenType
19        || (arena.data_types.get(value) == EnumToken::WildCardFunctionTokenType && arena.string_equals_ignore_case(arena.string_value.get(value), "if"))
20}
21
22/// deep clone a declaration. the clone map is filled with the cloned value tokens
23fn clone_declaration(arena: &AstArena, declaration: u32, node_map: &mut HashMap<u32, u32>) -> u32 {
24    node_map.clear();
25    arena.clone_node_deep(declaration, true, Some(node_map))
26}
27
28/// create an at-rule wrapping a declaration. the location is inherited from the declaration parent
29fn create_at_rule(arena: &AstArena, declaration: u32, parent: u32, nam: &str, tokens: &[u32], options: &ParserOptions) -> u32 {
30    let value: String = tokens.iter().map(|&t| render_value(arena, t, options)).collect();
31    let at_rule = arena.create_at_rule(EnumToken::AtRuleNodeType, StrOrId::Str(nam), StrOrId::Str(&value), true, Some(tokens), 0, None);
32    let parent = if arena.parents.get(declaration) != 0 { arena.parents.get(declaration) } else { parent };
33    if parent != 0 {
34        arena.copy_location(at_rule, parent);
35    }
36    at_rule
37}
38
39/// first token of the left side of an if condition that is not a comment or a whitespace
40fn condition_left(arena: &AstArena, condition: u32) -> Option<u32> {
41    arena
42        .field_tokens(condition, TokenField::L)
43        .into_iter()
44        .find(|&t| !matches!(arena.data_types.get(t), EnumToken::CommentTokenType | EnumToken::WhitespaceTokenType))
45}
46
47/// value tokens of an if condition (right side), mapped to their clones. the trailing semicolon is removed
48fn condition_value(arena: &AstArena, condition: u32, node_map: &HashMap<u32, u32>) -> Vec<u32> {
49    let mut tokens = arena.field_tokens(condition, TokenField::R);
50    if tokens.last().is_some_and(|&l| arena.data_types.get(l) == EnumToken::SemiColonTokenType) {
51        tokens.pop();
52        trim_array(arena, &mut tokens);
53    }
54    tokens.iter().map(|t| node_map.get(t).copied().unwrap_or(0)).collect()
55}
56
57/// `arena.replaceToken(target, ...tokens)`: an unmapped target (`undefined`) is ignored
58fn replace(arena: &AstArena, target: u32, tokens: &[u32]) {
59    if target != 0 {
60        arena.replace_token(target, tokens);
61    }
62}
63
64fn is_else(arena: &AstArena, token: u32) -> bool {
65    arena.data_types.get(token) == EnumToken::IdenTokenType && arena.string_equals_ignore_case(arena.string_value.get(token), "else")
66}
67
68fn substitute_if_else_node(arena: &AstArena, declaration: u32, node: u32, wrapper: u32, parent_wrapper: u32, parent: u32) -> Vec<u32> {
69    let mut result: Vec<u32> = Vec::new();
70    let mut node_map: HashMap<u32, u32> = HashMap::default();
71    // map a token or the declaration itself to its clone
72    let mapped = |target: u32, cloned: u32, map: &HashMap<u32, u32>| if target == declaration { cloned } else { map.get(&target).copied().unwrap_or(0) };
73    let typ = arena.data_types.get(node);
74    if typ == EnumToken::IfElseConditionTokenType {
75        let mut cloned = clone_declaration(arena, declaration, &mut node_map);
76        let else_condition = arena.field(node, TokenField::R);
77        // replace else: ... with the actual value
78        if arena.data_types.get(else_condition) == EnumToken::IfConditionTokenType {
79            if let Some(target) = condition_left(arena, else_condition).filter(|&t| is_else(arena, t)) {
80                let _ = target;
81                let value = condition_value(arena, else_condition, &node_map);
82                replace(arena, mapped(wrapper, cloned, &node_map), &value);
83                if parent_wrapper != declaration {
84                    let siblings = arena.tokens(parent_wrapper);
85                    if let Some(index) = siblings.iter().position(|&s| s == wrapper) {
86                        let left = condition_left(arena, arena.field(node, TokenField::L));
87                        for &sibling in &siblings[index + 1..] {
88                            if arena.data_types.get(sibling) != arena.data_types.get(wrapper) {
89                                continue;
90                            }
91                            for child in arena.tokens(sibling) {
92                                if arena.data_types.get(child) != EnumToken::IfElseConditionTokenType {
93                                    continue;
94                                }
95                                let left_side = condition_left(arena, arena.field(child, TokenField::L));
96                                if let (Some(l), Some(ls)) = (left, left_side) {
97                                    if eq_token(arena, l, ls) {
98                                        let value = condition_value(arena, arena.field(child, TokenField::R), &node_map);
99                                        replace(arena, mapped(sibling, cloned, &node_map), &value);
100                                    }
101                                }
102                            }
103                        }
104                    }
105                }
106            }
107        }
108        result.push(cloned);
109        cloned = clone_declaration(arena, declaration, &mut node_map);
110        let l = mapped(arena.field(node, TokenField::L), cloned, &node_map);
111        replace(arena, mapped(wrapper, cloned, &node_map), &[l]);
112        result.push(cloned);
113    } else if typ == EnumToken::IfConditionTokenType {
114        let Some(left) = condition_left(arena, node) else {
115            return result;
116        };
117        let left_type = arena.data_types.get(left);
118        if is_else(arena, left) {
119            let cloned = clone_declaration(arena, declaration, &mut node_map);
120            let target = if wrapper == declaration { node } else { wrapper };
121            let value = condition_value(arena, node, &node_map);
122            replace(arena, mapped(target, cloned, &node_map), &value);
123            result.push(cloned);
124        } else if left_type == EnumToken::WhenElseFunctionTokenType {
125            let name = arena.resolve_string(arena.string_value.get(left));
126            let minify = name != "supports";
127            let options = ParserOptions { minify: Some(minify), convert_color: Some(ConvertColor::Bool(minify)), ..Default::default() };
128            let inner: Vec<u32> = arena.tokens(left).into_iter().map(|t| arena.clone_node_deep(t, true, None)).collect();
129            let parens = arena.create_list(EnumToken::ParensTokenType, Some(&inner));
130            let at_rule = create_at_rule(arena, declaration, parent, &name, &[parens], &options);
131            let cloned = clone_declaration(arena, declaration, &mut node_map);
132            let value = condition_value(arena, node, &node_map);
133            replace(arena, mapped(node, cloned, &node_map), &value);
134            arena.append_child_list(at_rule, &[cloned]);
135            result.push(at_rule);
136            process_node(arena, cloned, parent);
137        } else if left_type == EnumToken::ContainerFunctionTokenType {
138            let left_clone = arena.clone_node_deep(left, true, None);
139            let at_rule = create_at_rule(arena, declaration, parent, "container", &[left_clone], &ParserOptions::default());
140            let cloned = clone_declaration(arena, declaration, &mut node_map);
141            let is_wild_card = wrapper != declaration && arena.data_types.get(wrapper) == EnumToken::WildCardFunctionTokenType;
142            let value = condition_value(arena, node, &node_map);
143            replace(arena, mapped(if is_wild_card { wrapper } else { node }, cloned, &node_map), &value);
144            arena.append_child_list(at_rule, &[cloned]);
145            result.push(at_rule);
146            process_node(arena, cloned, parent);
147        }
148    }
149    result
150}
151
152/// expand the if() conditions of a declaration into declarations / at-rules
153fn process_node(arena: &AstArena, declaration_node: u32, parent: u32) -> Vec<u32> {
154    let mut result: Vec<u32> = Vec::new();
155    let mut stack: Vec<u32> = vec![declaration_node];
156    // the generated nodes are detached: the parent gives the location of the generated at-rules
157    let parent = if arena.parents.get(declaration_node) != 0 { arena.parents.get(declaration_node) } else { parent };
158    let mut k = 0;
159    while k < stack.len() {
160        let ast_node = stack[k];
161        k += 1;
162        let Some((declaration, value)) = arena.find_by_value(ast_node, is_if_token) else {
163            result.push(ast_node);
164            continue;
165        };
166        // the parent of a detached token is the declaration
167        let parent_wrapper = match arena.get_value_parent(value) {
168            0 => declaration,
169            p => p,
170        };
171        let grand_parent = if parent_wrapper == declaration {
172            declaration
173        } else {
174            match arena.get_value_parent(parent_wrapper) {
175                0 => declaration,
176                p => p,
177            }
178        };
179        if arena.data_types.get(value) == EnumToken::WildCardFunctionTokenType {
180            for condition in arena.tokens(value) {
181                stack.extend(substitute_if_else_node(arena, declaration, condition, value, parent_wrapper, parent));
182            }
183        } else {
184            stack.extend(substitute_if_else_node(arena, declaration, value, parent_wrapper, grand_parent, parent));
185        }
186        // the node is substituted: release it unless it is the node being replaced
187        if ast_node != declaration_node {
188            arena.detach(ast_node);
189        }
190    }
191    if !result.is_empty() && arena.parents.get(declaration_node) != 0 {
192        arena.replace_child(declaration_node, &result);
193        if !result.contains(&declaration_node) {
194            arena.detach(declaration_node);
195        }
196    }
197    result
198}
199
200pub struct ExpandIfFeature;
201
202const ACCEPT: [u8; 1] = [EnumToken::DeclarationNodeType];
203
204impl ExpandIfFeature {
205    pub fn register(options: &ParserOptions, features: &mut Vec<SharedFeature>) {
206        if options.expand_if_syntax == Some(true) {
207            features.push(Rc::new(RefCell::new(ExpandIfFeature)));
208        }
209    }
210}
211
212impl MinifyFeature for ExpandIfFeature {
213    fn accept(&self) -> Option<&[u8]> {
214        Some(&ACCEPT)
215    }
216
217    fn ordering(&self) -> i32 {
218        1
219    }
220
221    fn process_mode(&self) -> u32 {
222        FeatureWalkMode::Pre
223    }
224
225    fn run(&mut self, arena: &AstArena, declaration: u32, _options: &ParserOptions, _parent: u32, _context: &mut MinifyContext, _mode: u32) -> FeatureResult {
226        FeatureResult::Nodes(process_node(arena, declaration, 0))
227    }
228}