Skip to main content

rust_css_parser/parser/declaration/
set.rs

1//! Port of `src/parser/declaration/set.ts`.
2
3use super::{str_list, JsMap};
4use crate::ast::arena::{is_numeric_token_type, AstArena, StrOrId, TokenValue};
5use crate::ast::types::{EnumAstNodeStatus, EnumToken};
6use crate::parser::utils::eq::eq_token;
7use crate::syntax::syntax::is_length;
8use serde_json::Value;
9
10fn dedup(arena: &AstArena, values: &mut [Vec<u32>]) {
11    let t = |x: u32| arena.data_types.get(x);
12    for value in values.iter_mut() {
13        let mut i = value.len();
14        while i > 1 {
15            i -= 1;
16            let tk = value[i];
17            let k = value[if i == 1 { 0 } else { i % 2 }];
18            if is_numeric_token_type(t(tk))
19                && is_numeric_token_type(t(k))
20                && arena.numeric_value.get(tk) == 0.0
21                && arena.numeric_value.get(k) == 0.0
22                && !arena.has_fraction(tk)
23                && !arena.has_fraction(k)
24                && ((t(tk) == EnumToken::NumberTokenType && is_length(arena, k))
25                    || (t(k) == EnumToken::NumberTokenType && is_length(arena, tk))
26                    || is_length(arena, k)
27                    || is_length(arena, tk))
28            {
29                value.remove(i);
30                continue;
31            }
32            if eq_token(arena, tk, k) {
33                value.remove(i);
34                continue;
35            }
36            break;
37        }
38    }
39}
40
41/// set of declarations that can be merged into a single shorthand declaration
42pub struct PropertySet {
43    config: &'static Value,
44    pub declarations: JsMap<u32>,
45}
46
47impl PropertySet {
48    pub fn new(config: &'static Value) -> Self {
49        Self { config, declarations: JsMap::new() }
50    }
51
52    fn shorthand(&self) -> &'static str {
53        self.config["shorthand"].as_str().unwrap_or("")
54    }
55
56    pub fn add(&mut self, arena: &AstArena, declaration: u32) -> &mut Self {
57        let nam = arena.resolve_string(arena.name.get(declaration));
58        let shorthand = self.shorthand();
59        if nam == shorthand {
60            self.declarations = JsMap::new();
61        } else if let Some(&existing) = self.declarations.get(shorthand) {
62            // expand the shorthand
63            let types = str_list(&self.config["types"]);
64            let keywords = str_list(&self.config["keywords"]);
65            let separator = self.config.get("separator").and_then(|s| s.get("val")).and_then(|v| v.as_str());
66            let mut is_valid = true;
67            let mut tokens: Vec<Vec<u32>> = Vec::new();
68            for token in arena.token_iter(existing) {
69                let typ = arena.data_types.get(token);
70                if types.iter().any(|t| EnumToken::value(t) == Some(typ))
71                    || (typ == EnumToken::NumberTokenType
72                        && arena.numeric_value.get(token) == 0.0
73                        && (types.contains(&"Length") || types.contains(&"Angle") || types.contains(&"Dimension")))
74                {
75                    if tokens.is_empty() {
76                        tokens.push(Vec::new());
77                    }
78                    tokens.last_mut().unwrap().push(token);
79                    continue;
80                }
81                if typ != EnumToken::WhitespaceTokenType && typ != EnumToken::CommentTokenType {
82                    if typ == EnumToken::IdenTokenType && keywords.contains(&&*arena.resolve_string(arena.string_value.get(token))) {
83                        if tokens.is_empty() {
84                            tokens.push(Vec::new());
85                        }
86                        tokens.last_mut().unwrap().push(token);
87                    }
88                    if typ == EnumToken::LiteralTokenType && separator.is_some_and(|s| arena.string_equals(arena.string_value.get(token), s)) {
89                        tokens.push(Vec::new());
90                        continue;
91                    }
92                    is_valid = false;
93                    break;
94                }
95            }
96            if is_valid && !tokens.is_empty() {
97                self.declarations.delete(shorthand);
98                let properties = str_list(&self.config["properties"]);
99                for values in &tokens {
100                    for (index, property) in properties.iter().enumerate() {
101                        if !self.declarations.has(property) {
102                            let node = arena.create_declaration(EnumToken::DeclarationNodeType, StrOrId::Str(property), Some(&[]), 0, None);
103                            self.declarations.set(*property, node);
104                        }
105                        let mut index = index;
106                        while index > 0 && index >= values.len() {
107                            if index > 1 {
108                                index %= 2;
109                            } else {
110                                index = 0;
111                                break;
112                            }
113                        }
114                        let node = *self.declarations.get(property).unwrap();
115                        if arena.first_token.get(node) != 0 {
116                            arena.append_token(node, arena.create_token(EnumToken::WhitespaceTokenType, TokenValue::None, None));
117                        }
118                        // typescript: `values[index]` may be undefined
119                        if let Some(&value) = values.get(index) {
120                            arena.append_token(node, arena.clone_node_deep(value, true, None));
121                        }
122                    }
123                }
124            }
125            self.declarations.set(nam, declaration);
126            return self;
127        }
128        self.declarations.set(nam, declaration);
129        self
130    }
131
132    pub fn is_shorthand(&self) -> bool {
133        if self.declarations.has(self.shorthand()) {
134            return self.declarations.len() == 1;
135        }
136        self.config["properties"].as_array().map_or(0, |a| a.len()) == self.declarations.len()
137    }
138
139    /// the declarations: the merged shorthand when the set is complete (`[Symbol.iterator]()`)
140    pub fn iterate(&mut self, arena: &AstArena) -> Vec<u32> {
141        let values: Vec<u32> = self.declarations.values().copied().collect();
142        let properties = str_list(&self.config["properties"]);
143        // the !important declarations are not merged
144        if !self.declarations.has(self.shorthand()) && values.iter().any(|&d| arena.flags.get(d) & EnumAstNodeStatus::ImportantDeclaration != 0) {
145            return values;
146        }
147        if self.declarations.len() < properties.len() {
148            if self.is_shorthand() {
149                let val: Vec<u32> = arena
150                    .tokens(values[0])
151                    .into_iter()
152                    .filter(|&c| !matches!(arena.data_types.get(c), EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType))
153                    .collect();
154                let mut list: Vec<u32> = Vec::new();
155                for curr in val {
156                    if !list.is_empty() {
157                        list.push(arena.create_token(EnumToken::WhitespaceTokenType, TokenValue::None, None));
158                    }
159                    list.push(curr);
160                }
161                arena.set_token_list(values[0], &list);
162            }
163            return values;
164        }
165        let mut groups: Vec<Vec<u32>> = Vec::new();
166        for property in &properties {
167            let mut index = 0;
168            let tokens = self.declarations.get(property).map_or_else(Vec::new, |&id| arena.tokens(id));
169            for token in tokens {
170                if arena.data_types.get(token) == EnumToken::WhitespaceTokenType {
171                    continue;
172                }
173                if groups.len() == index {
174                    groups.push(Vec::new());
175                }
176                groups[index].push(token);
177                index += 1;
178            }
179        }
180        if self.config.get("valueSeparator").is_none_or(|v| v.is_null()) {
181            dedup(arena, &mut groups);
182        }
183        let separator = self.config.get("separator").and_then(|s| s.get("val")).and_then(|v| v.as_str());
184        let mut acc: Vec<u32> = Vec::new();
185        for mut curr in groups {
186            if curr.len() > 1 {
187                let k = curr.len() * 2 - 1;
188                let mut i = 1;
189                while i < k {
190                    curr.insert(i, arena.create_token(EnumToken::WhitespaceTokenType, TokenValue::None, None));
191                    i += 2;
192                }
193            }
194            if !acc.is_empty() {
195                acc.push(arena.create_token(EnumToken::LiteralTokenType, separator.map_or(TokenValue::None, TokenValue::Str), None));
196            }
197            for token in curr {
198                // tokens are shared with the original declarations
199                acc.push(if arena.parents.get(token) != 0 { arena.clone_node_deep(token, true, None) } else { token });
200            }
201        }
202        vec![arena.create_declaration(EnumToken::DeclarationNodeType, StrOrId::Str(self.shorthand()), Some(&acc), 0, None)]
203    }
204}