Skip to main content

rust_css_parser/parser/declaration/
list.rs

1//! Port of `src/parser/declaration/list.ts`.
2
3use super::map::PropertyMap;
4use super::set::PropertySet;
5use super::{flatten, has_key, DeclEntry, JsMap};
6use crate::ast::arena::{AstArena, TokenValue};
7use crate::ast::cache::StructuralMemo;
8use crate::ast::types::{EnumAstNodeStatus, EnumToken};
9use crate::options::{ParserOptions, RemoveDuplicateDeclarations};
10use crate::parser::parse::parse_string;
11use crate::parser::utils::config::{config_index, ConfigIndex};
12use crate::parser::utils::text::{equals_ignore_case, lowercase};
13use crate::validation::config::get_parsed_syntax;
14use crate::validation::match_::{is_valid_declaration_value, Syntax};
15use crate::validation::parser::typedef::ValidationSyntaxGroupEnum;
16use serde_json::Value;
17use std::cell::RefCell;
18use crate::utils::fx::HashMap;
19use std::rc::Rc;
20use crate::ast::strings::SharedStr;
21
22/// results shared by the property lists of a minification, valid for the arena they were computed for: the keys of
23/// the declarations that are not merged by name (identical declarations have the same key) and the tokens of the
24/// default values (each value is parsed once, the tokens are cloned)
25pub struct DeclarationMemo {
26    /// key by structure. same equality as the structural signature
27    keys: StructuralMemo<Rc<str>>,
28    /// parsed values: detached tokens that are cloned, never attached to the tree
29    parsed: HashMap<String, Vec<u32>>,
30}
31
32impl Default for DeclarationMemo {
33    fn default() -> Self {
34        Self { keys: StructuralMemo::new(true), parsed: HashMap::default() }
35    }
36}
37
38impl DeclarationMemo {
39    /// tokens of a value: the value is parsed once, the tokens are cloned
40    pub fn parse(&mut self, arena: &AstArena, value: &str) -> Vec<u32> {
41        let template = self.parsed.entry(value.to_string()).or_insert_with(|| parse_string(arena, value));
42        template.iter().map(|&t| arena.clone_node_deep(t, true, None)).collect()
43    }
44
45    /// unique key of the structure of a node: identical nodes have the same key
46    pub fn key(&mut self, arena: &AstArena, node: u32) -> Rc<str> {
47        let slot = self.keys.token(arena, node);
48        if let Some(key) = self.keys.get(slot) {
49            return key.clone();
50        }
51        // not a property name
52        let key: Rc<str> = Rc::from(format!("\0{}", slot));
53        self.keys.set(slot, key.clone());
54        key
55    }
56}
57
58/// true if the value of a declaration contains var(), env() or if()
59fn has_wild_card_function(arena: &AstArena, declaration: u32) -> bool {
60    arena
61        .tokens(declaration)
62        .iter()
63        .any(|&t| matches!(arena.data_types.get(t), EnumToken::WildCardFunctionTokenType | EnumToken::WildCardFunctionTokenDefType))
64}
65
66/// a list of declarations: computes the shorthands and removes the duplicate declarations
67pub struct PropertyList<'o> {
68    options: &'o ParserOptions,
69    declarations: JsMap<DeclEntry>,
70    memo: Rc<RefCell<DeclarationMemo>>,
71    /// syntaxes of the descriptors of the at-rule that contains the declarations (`result` in `@function`)
72    descriptors: Option<Rc<HashMap<String, Rc<Vec<Syntax>>>>>,
73}
74
75impl<'o> PropertyList<'o> {
76    pub fn new(options: &'o ParserOptions, memo: Option<Rc<RefCell<DeclarationMemo>>>, descriptors: Option<Rc<HashMap<String, Rc<Vec<Syntax>>>>>) -> Self {
77        Self { options, declarations: JsMap::new(), memo: memo.unwrap_or_default(), descriptors }
78    }
79
80    fn key(&self, arena: &AstArena, node: u32) -> Rc<str> {
81        self.memo.borrow_mut().key(arena, node)
82    }
83
84    /// keep the declaration by key: a previous identical declaration is replaced (moved to the end)
85    fn set_by_key(&mut self, arena: &AstArena, declaration: u32) {
86        let key = self.key(arena, declaration);
87        self.declarations.delete(&key);
88        self.declarations.set(key, DeclEntry::Node(declaration));
89    }
90
91    /// add a declaration
92    pub fn add_declaration(&mut self, arena: &AstArena, declaration: u32) -> &mut Self {
93        if arena.data_types.get(declaration) != EnumToken::DeclarationNodeType {
94            let key = self.key(arena, declaration);
95            self.declarations.set(key, DeclEntry::Node(declaration));
96            return self;
97        }
98        // the interned name, shared: no copy
99        let name: SharedStr = arena.resolve_string(arena.name.get(declaration));
100        let flags = arena.flags.get(declaration);
101        // @function / result
102        if flags & EnumAstNodeStatus::Unknown != 0 && equals_ignore_case("result", &name) {
103            self.declarations.set(name, DeclEntry::Node(declaration));
104            return self;
105        }
106        let keep_duplicates = match &self.options.remove_duplicate_declarations {
107            Some(RemoveDuplicateDeclarations::Names(names)) => names.iter().any(|n| **n == *name),
108            Some(RemoveDuplicateDeclarations::Bool(b)) => !b,
109            None => true,
110        };
111        if flags & (EnumAstNodeStatus::Invalid | EnumAstNodeStatus::Unknown | EnumAstNodeStatus::ValidationFailed) != 0
112            || equals_ignore_case("composes", &name)
113            || keep_duplicates
114        {
115            self.set_by_key(arena, declaration);
116            return self;
117        }
118        if self.options.compute_shorthand != Some(true) {
119            self.declarations.set(name, DeclEntry::Node(declaration));
120            return self;
121        }
122        if arena.flags.get(declaration) & EnumAstNodeStatus::Unvalidated != 0 {
123            let lower = lowercase(&name);
124            let syntax_rules: Option<Rc<Vec<Syntax>>> =
125                self.descriptors.as_ref().and_then(|d| d.get(&*lower).cloned()).or_else(|| get_parsed_syntax(ValidationSyntaxGroupEnum::Declarations, &lower));
126            if let Some(rules) = syntax_rules {
127                let state = if is_valid_declaration_value(arena, &rules, declaration, self.options) {
128                    EnumAstNodeStatus::Validated
129                } else {
130                    EnumAstNodeStatus::ValidationFailed
131                };
132                arena.flags.set(declaration, arena.flags.get(declaration) | (state & !EnumAstNodeStatus::Unvalidated));
133            }
134        }
135        // do not compute shorthand for invalid declarations
136        if arena.flags.get(declaration) & EnumAstNodeStatus::Validated == 0 {
137            self.set_by_key_no_delete(arena, declaration);
138            return self;
139        }
140        let property_name = name.clone();
141        let index = config_index();
142        let (short_hand_type, shorthand): (&str, Option<&'static Value>) = if let Some(p) = index.properties.get(&*property_name) {
143            if has_key(p, "map") {
144                ("map", p.get("map"))
145            } else {
146                ("set", p.get("shorthand"))
147            }
148        } else if let Some(m) = index.map.get(&*property_name) {
149            ("map", m.get("shorthand"))
150        } else if let Some(p) = index.property.get(&*property_name) {
151            ("single", Some(*p))
152        } else {
153            ("", None)
154        };
155        let shorthand_name: Option<&'static str> = shorthand.and_then(|s| s.as_str());
156        // the value of a shorthand that contains var(), env() or if() cannot be expanded
157        if shorthand_name == Some(&*name) && (short_hand_type == "map" || short_hand_type == "set") && has_wild_card_function(arena, declaration) {
158            self.set_by_key_no_delete(arena, declaration);
159            return self;
160        }
161        if let Some(sh) = shorthand_name {
162            if let Some(existing) = self.declarations.get(sh) {
163                let existing: Option<u32> = match existing {
164                    DeclEntry::Node(n) => Some(*n),
165                    DeclEntry::Set(s) => s.borrow().declarations.get(&name).copied(),
166                    DeclEntry::Map(m) => match m.borrow().declarations.get(&name) {
167                        Some(DeclEntry::Node(n)) => Some(*n),
168                        _ => None,
169                    },
170                };
171                if let Some(existing) = existing {
172                    if arena.flags.get(existing) & EnumAstNodeStatus::ImportantDeclaration != 0
173                        && arena.flags.get(declaration) & EnumAstNodeStatus::ImportantDeclaration == 0
174                    {
175                        return self;
176                    }
177                }
178            }
179        }
180        match short_hand_type {
181            "map" => {
182                let shorthand = shorthand_name.unwrap_or("");
183                let map_name = index.map.get(&*property_name).and_then(|m| m.get("map")).and_then(|m| m.as_str()).or_else(|| {
184                    index.map.get(shorthand).and_then(|s| s.get("properties")).and_then(|p| p.get(&*property_name)).and_then(|p| p.get("map")).and_then(|m| m.as_str())
185                });
186                let memo = Some(self.memo.clone());
187                match map_name {
188                    Some(map_name) => {
189                        if !self.declarations.has(map_name) {
190                            self.declarations.set(SharedStr::from_static(map_name), DeclEntry::Map(Rc::new(RefCell::new(PropertyMap::new(ConfigIndex::get(&index.map, map_name), memo.clone())))));
191                        }
192                        let Some(DeclEntry::Map(owner)) = self.declarations.get(map_name).cloned() else {
193                            return self;
194                        };
195                        if !owner.borrow().declarations.has(shorthand) {
196                            owner.borrow_mut().declarations.set(SharedStr::from_static(shorthand), DeclEntry::Map(Rc::new(RefCell::new(PropertyMap::new(ConfigIndex::get(&index.map, shorthand), memo)))));
197                        }
198                        let target = owner.borrow().declarations.get(shorthand).cloned();
199                        if let Some(DeclEntry::Map(target)) = target {
200                            target.borrow_mut().add(arena, declaration);
201                        }
202                    }
203                    None => {
204                        if !self.declarations.has(shorthand) {
205                            self.declarations.set(SharedStr::from_static(shorthand), DeclEntry::Map(Rc::new(RefCell::new(PropertyMap::new(ConfigIndex::get(&index.map, shorthand), memo)))));
206                        }
207                        if let Some(DeclEntry::Map(target)) = self.declarations.get(shorthand).cloned() {
208                            target.borrow_mut().add(arena, declaration);
209                        }
210                    }
211                }
212            }
213            "set" => {
214                let shorthand = shorthand_name.unwrap_or("");
215                if !self.declarations.has(shorthand) {
216                    self.declarations.set(SharedStr::from_static(shorthand), DeclEntry::Set(Rc::new(RefCell::new(PropertySet::new(ConfigIndex::get(&index.properties, shorthand))))));
217                }
218                if let Some(DeclEntry::Set(set)) = self.declarations.get(shorthand).cloned() {
219                    set.borrow_mut().add(arena, declaration);
220                }
221            }
222            _ => {
223                if let Some(mapping) = shorthand.filter(|s| !s.is_null()) {
224                    self.map_values(arena, declaration, mapping);
225                }
226                // a previous declaration with the same name takes precedence when it is !important and the new one is not
227                if let Some(DeclEntry::Node(existing)) = self.declarations.get(&*property_name) {
228                    if arena.flags.get(*existing) & EnumAstNodeStatus::ImportantDeclaration != 0
229                        && arena.flags.get(declaration) & EnumAstNodeStatus::ImportantDeclaration == 0
230                    {
231                        return self;
232                    }
233                }
234                self.declarations.set(property_name, DeclEntry::Node(declaration));
235            }
236        }
237        self
238    }
239
240    /// `declarations.set(memo.key(declaration), declaration)`
241    fn set_by_key_no_delete(&mut self, arena: &AstArena, declaration: u32) {
242        let key = self.key(arena, declaration);
243        self.declarations.set(key, DeclEntry::Node(declaration));
244    }
245
246    /// map the values of a single property (`mapValues()`)
247    fn map_values(&mut self, arena: &AstArena, declaration: u32, mapping: &Value) {
248        let declaration_values = arena.tokens(declaration);
249        let mut values: Option<Vec<u32>> = None;
250        if let Some(patterns_list) = mapping.get("pattern").and_then(|p| p.as_array()) {
251            for patterns in patterns_list {
252                // insertion ordered set
253                let mut set: Vec<u32> = declaration_values
254                    .iter()
255                    .copied()
256                    .filter(|&v| !matches!(arena.data_types.get(v), EnumToken::CommentTokenType | EnumToken::WhitespaceTokenType))
257                    .collect();
258                let mut val: Vec<u32> = Vec::new();
259                for pattern in super::str_list(patterns) {
260                    if pattern == "<length>" {
261                        // falls through to the default case
262                        set.retain(|&v| {
263                            let matched = arena.data_types.get(v) == EnumToken::LengthTokenType
264                                || (arena.data_types.get(v) == EnumToken::NumberTokenType && arena.numeric_value.get(v) == 0.0);
265                            if matched {
266                                val.push(v);
267                            }
268                            !matched
269                        });
270                    }
271                    set.retain(|&v| {
272                        if arena.data_types.get(v) != EnumToken::IdenTokenType {
273                            return true;
274                        }
275                        let value = arena.resolve_string(arena.string_value.get(v)).to_lowercase();
276                        let matched = value == pattern || delimited_match(&value, pattern);
277                        if matched {
278                            val.push(v);
279                        }
280                        !matched
281                    });
282                }
283                if set.is_empty() {
284                    let mut list: Vec<u32> = Vec::new();
285                    for curr in val {
286                        if !list.is_empty() {
287                            list.push(arena.create_token(EnumToken::WhitespaceTokenType, TokenValue::None, None));
288                        }
289                        list.push(curr);
290                    }
291                    values = Some(list);
292                    break;
293                }
294            }
295        }
296        for &val in &declaration_values {
297            if arena.data_types.get(val) == EnumToken::IdenTokenType {
298                let name = arena.resolve_string(arena.string_value.get(val)).to_lowercase();
299                if let Some(m) = mapping.get("mapping").and_then(|m| m.get(&name)).filter(|m| !m.is_null()) {
300                    let typ = m.get("typ").and_then(|t| t.as_str()).and_then(EnumToken::value).unwrap_or(0);
301                    let v = m.get("val");
302                    let value = match v {
303                        Some(Value::String(s)) => TokenValue::Str(s),
304                        Some(Value::Number(n)) => TokenValue::Num(n.as_f64().unwrap_or(0.0)),
305                        _ => TokenValue::None,
306                    };
307                    arena.reset_token(val, typ, value, None);
308                }
309            }
310        }
311        if let Some(values) = values {
312            arena.set_token_list(declaration, &values);
313        }
314    }
315
316    /// the declarations of the list, the shorthands computed (`[Symbol.iterator]()`)
317    pub fn iterate(&mut self, arena: &AstArena) -> Vec<u32> {
318        flatten(arena, self.declarations.values())
319    }
320}
321
322/// `new RegExp("(^|\\|)" + pattern + "(\\||$)").test(value)`. the pattern is not grouped: `a|b|c` is the alternation
323/// of `(^|\|)a`, `b` and `c(\||$)`
324fn delimited_match(value: &str, pattern: &str) -> bool {
325    let alternatives: Vec<&str> = pattern.split('|').collect();
326    let last = alternatives.len() - 1;
327    alternatives.iter().enumerate().any(|(i, alt)| {
328        let starts = i == 0;
329        let ends = i == last;
330        value.match_indices(alt).any(|(at, _)| {
331            let end = at + alt.len();
332            let before = !starts || at == 0 || value.as_bytes()[at - 1] == b'|';
333            let after = !ends || end == value.len() || value.as_bytes()[end] == b'|';
334            before && after
335        }) || (alt.is_empty() && (!starts || !ends || value.is_empty() || value.contains('|')))
336    })
337}