1use super::list::DeclarationMemo;
4use super::set::PropertySet;
5use super::{config_token, config_type, flatten, has_key, match_config_token, str_list, DeclEntry, JsMap};
6use crate::ast::arena::{AstArena, StrOrId, TokenValue};
7use crate::ast::types::EnumToken;
8use crate::options::ParserOptions;
9use crate::parser::parse::parse_string;
10use crate::parser::utils::config::get_config;
11use crate::parser::utils::eq::eq_token;
12use crate::parser::utils::type_::match_type;
13use crate::printer::render::render_value;
14use serde_json::Value;
15use std::cell::RefCell;
16use crate::utils::fx::HashMap;
17use std::rc::Rc;
18
19struct TokenMap {
21 t: Vec<u32>,
22 value: Vec<String>,
23}
24
25fn truthy(v: Option<&Value>) -> bool {
26 match v {
27 None | Some(Value::Null) => false,
28 Some(Value::Bool(b)) => *b,
29 Some(Value::Number(n)) => n.as_f64().is_some_and(|n| n != 0.0),
30 Some(Value::String(s)) => !s.is_empty(),
31 Some(_) => true,
32 }
33}
34
35fn non_null(v: Option<&Value>) -> Option<&Value> {
36 v.filter(|v| !v.is_null())
37}
38
39thread_local! {
40 static MAP_SETTINGS: RefCell<HashMap<usize, (usize, Rc<[Rc<str>]>)>> = RefCell::new(HashMap::default());
43}
44
45fn map_settings(config: &'static Value) -> (usize, Rc<[Rc<str>]>) {
47 let key = config as *const Value as usize;
48 if let Some(settings) = MAP_SETTINGS.with(|m| m.borrow().get(&key).cloned()) {
49 return settings;
50 }
51 let values: Vec<&Value> = config["properties"].as_object().map(|o| o.values().collect()).unwrap_or_default();
52 let required = values.iter().filter(|v| truthy(v.get("required"))).count();
53 let required_count = if required == 0 { values.len() } else { required };
54 let pattern: Rc<[Rc<str>]> = config["pattern"].as_str().unwrap_or("").split(char::is_whitespace).map(Rc::from).collect();
55 MAP_SETTINGS.with(|m| m.borrow_mut().insert(key, (required_count, pattern.clone())));
56 (required_count, pattern)
57}
58
59pub struct PropertyMap {
61 pub declarations: JsMap<DeclEntry>,
62 pub config: &'static Value,
63 required_count: usize,
64 pattern: Rc<[Rc<str>]>,
65 pub property_names: HashMap<u32, Rc<str>>,
67 memo: Option<Rc<RefCell<DeclarationMemo>>>,
69}
70
71impl PropertyMap {
72 pub fn new(config: &'static Value, memo: Option<Rc<RefCell<DeclarationMemo>>>) -> Self {
73 let (required_count, pattern) = map_settings(config);
74 Self { declarations: JsMap::new(), config, required_count, pattern, property_names: HashMap::default(), memo }
75 }
76
77 fn shorthand(&self) -> &'static str {
78 self.config["shorthand"].as_str().unwrap_or("")
79 }
80
81 fn props(&self, property: &str) -> &'static Value {
82 &self.config["properties"][property]
83 }
84
85 fn parse(&self, arena: &AstArena, value: &str) -> Vec<u32> {
87 match &self.memo {
88 None => parse_string(arena, value),
89 Some(memo) => memo.borrow_mut().parse(arena, value),
90 }
91 }
92
93 pub fn add(&mut self, arena: &AstArena, declaration: u32) -> &mut Self {
94 let nam = arena.resolve_string(arena.name.get(declaration));
95 let shorthand = self.shorthand();
96 if nam == shorthand {
97 self.declarations.clear();
98 self.declarations.set(nam, DeclEntry::Node(declaration));
99 self.match_types(arena, declaration);
100 return self;
101 }
102 let separator = non_null(self.config.get("separator"));
103 if let Some(DeclEntry::Node(existing)) = self.declarations.get(shorthand).cloned() {
105 let mut tokens: JsMap<Vec<Vec<u32>>> = JsMap::new();
106 let mut values: Vec<u32> = Vec::new();
107 let mut val: Vec<Vec<u32>> = vec![Vec::new()];
108 for curr in arena.token_iter(existing) {
109 if match_config_token(arena, curr, separator) {
110 val.push(Vec::new());
111 continue;
112 }
113 val.last_mut().unwrap().push(curr);
114 }
115 for current in 0..val.len() {
116 let mut acc = std::mem::take(&mut val[current]);
117 for property in self.pattern.clone().iter() {
118 self.expand_property(arena, &mut acc, &property, current, &mut tokens);
119 }
120 values.extend(acc);
121 }
122 if values.is_empty() {
123 let mut declarations: JsMap<DeclEntry> = JsMap::new();
124 for (name, groups) in tokens.iter() {
125 let mut list: Vec<u32> = Vec::new();
126 for group in groups {
127 if !list.is_empty() {
128 list.push(config_token(arena, separator));
129 }
130 for &token in group {
131 list.push(self.take(arena, token));
132 }
133 }
134 let node = arena.create_declaration(EnumToken::DeclarationNodeType, StrOrId::Str(name), Some(&list), 0, None);
135 declarations.set(name, DeclEntry::Node(node));
136 }
137 self.declarations = declarations;
138 }
139 }
140 let properties_config = &get_config()["properties"];
141 match non_null(properties_config.get(&*nam)) {
142 Some(config) => {
143 let property = config["shorthand"].as_str().unwrap_or("").to_string();
144 let value = self.declarations.get(&property).cloned();
145 let set = match value {
146 Some(DeclEntry::Set(set)) => set,
147 other => {
148 let set = Rc::new(RefCell::new(PropertySet::new(&properties_config[property.as_str()])));
149 self.declarations.set(property.clone(), DeclEntry::Set(set.clone()));
150 if let Some(DeclEntry::Node(v)) = other {
151 set.borrow_mut().add(arena, v);
152 }
153 set
154 }
155 };
156 set.borrow_mut().add(arena, declaration);
157 }
158 None => self.declarations.set(nam, DeclEntry::Node(declaration)),
159 }
160 self
161 }
162
163 fn expand_property(&mut self, arena: &AstArena, acc: &mut Vec<u32>, property: &str, current: usize, tokens: &mut JsMap<Vec<Vec<u32>>>) {
165 let props = self.props(property);
166 let has_prefix = has_key(props, "prefix");
167 let filled = |tokens: &JsMap<Vec<Vec<u32>>>| tokens.get(property).is_some_and(|t| t.len() > current);
168 let mut i: isize = 0;
169 while (i as usize) < acc.len() {
170 let token = acc[i as usize];
171 if matches!(arena.data_types.get(token), EnumToken::CommentTokenType | EnumToken::WhitespaceTokenType) {
172 acc.remove(i as usize);
173 continue;
174 }
175 if self.property_names.get(&token).map(|n| &**n) == Some(property) || match_type(arena, token, props) {
176 if has_prefix {
177 if let Some(previous) = non_null(props.get("previous")).and_then(|p| p.as_str()) {
178 if !tokens.has(previous) {
179 return;
180 }
181 }
182 }
183 match tokens.get_mut(property) {
184 None => tokens.set(property, vec![vec![token]]),
185 Some(t) => {
186 if current == t.len() {
187 t.push(vec![token]);
188 } else if let Some(group) = t.get_mut(current) {
189 group.push(arena.create_token(EnumToken::WhitespaceTokenType, TokenValue::None, None));
190 group.push(token);
191 }
192 }
193 }
194 acc.remove(i as usize);
195 i -= 1;
196 if has_prefix && i >= 0 && match_config_token(arena, acc[i as usize], props.get("prefix")) {
197 acc.remove(i as usize);
198 i -= 1;
199 }
200 if truthy(props.get("multiple")) {
201 i += 1;
202 continue;
203 }
204 return;
205 } else if filled(tokens) {
206 return;
207 }
208 i += 1;
209 }
210 if filled(tokens) {
211 return;
212 }
213 let defaults = str_list(&props["default"]);
215 if let Some(default) = defaults.first() {
216 let parsed = self.parse(arena, default);
217 match tokens.get_mut(property) {
218 None => tokens.set(property, vec![parsed]),
219 Some(t) => {
220 if current == t.len() {
221 t.push(parsed);
222 } else if let Some(group) = t.get_mut(current) {
223 group.push(arena.create_token(EnumToken::WhitespaceTokenType, TokenValue::None, None));
224 group.extend(parsed);
225 }
226 }
227 }
228 }
229 }
230
231 pub fn iterate(&mut self, arena: &AstArena) -> Vec<u32> {
233 let properties_mapping = &self.config["properties"];
234 let mapping_entries: Vec<(&'static str, &'static Value)> =
235 properties_mapping.as_object().map(|o| o.iter().map(|(k, v)| (k.as_str(), v)).collect()).unwrap_or_default();
236 let patterns: Vec<&str> = self.config["pattern"].as_str().unwrap_or("").split(' ').collect();
237 let shorthand = self.shorthand();
238 let has_mapping = self.declarations.values().any(|v| matches!(v, DeclEntry::Map(_)));
239 let mut declarations: JsMap<DeclEntry> = self.declarations.clone();
240 if has_mapping {
241 let mut mapped: JsMap<DeclEntry> = JsMap::new();
242 for value in self.declarations.values().cloned().collect::<Vec<_>>() {
243 match value {
244 DeclEntry::Map(m) => {
245 let (entries, m_shorthand, m_config) = {
246 let mb = m.borrow();
247 (mb.declarations.iter().map(|(k, v)| (k.to_string(), v.clone())).collect::<Vec<_>>(), mb.shorthand(), mb.config)
248 };
249 for (k, v) in entries {
250 if k == m_shorthand {
251 let DeclEntry::Node(v) = v else {
252 continue;
253 };
254 let values = arena.tokens(v);
255 let keys: Vec<&str> = m_config["properties"].as_object().map(|o| o.keys().map(String::as_str).collect()).unwrap_or_default();
256 for key in keys {
257 let clone = arena.clone_node_deep(v, false, None);
258 mapped.set(key, DeclEntry::Node(clone));
259 let mut mapped_values: Vec<u32> = Vec::new();
260 for &value in &values {
261 let is_key = m.borrow().property_names.get(&value).map(|n| &**n) == Some(key);
262 if is_key {
263 if !mapped_values.is_empty() {
264 mapped_values.push(arena.create_token(EnumToken::WhitespaceTokenType, TokenValue::None, None));
265 }
266 let taken = m.borrow_mut().take(arena, value);
267 mapped_values.push(taken);
268 }
269 }
270 if mapped_values.is_empty() {
271 let default = m_config["properties"][key]["default"][0].as_str().unwrap_or("");
272 mapped_values.extend(self.parse(arena, default));
273 }
274 arena.set_token_list(clone, &mapped_values);
275 }
276 } else {
277 mapped.set(k, v);
278 }
279 }
280 }
281 DeclEntry::Set(_) => mapped.set("undefined", value),
283 DeclEntry::Node(n) => mapped.set(arena.resolve_string(arena.name.get(n)).to_string(), value),
284 }
285 }
286 if patterns.len() == mapped.len() {
287 declarations = JsMap::new();
288 for key in &patterns {
289 if let Some(v) = mapped.get(key) {
290 declarations.set(*key, v.clone());
291 }
292 }
293 }
294 }
295 let mut property: Option<&str> = None;
297 let mut required_count = 0usize;
298 let mut is_shorthand = true;
299 for &(key, cfg) in &mapping_entries {
300 property = Some(key);
301 if truthy(cfg.get("required")) {
302 match declarations.get(key) {
303 None => {
304 is_shorthand = false;
305 break;
306 }
307 Some(DeclEntry::Set(s)) if !s.borrow().is_shorthand() => {
308 is_shorthand = false;
309 break;
310 }
311 Some(_) => required_count += 1,
312 }
313 }
314 }
315 if required_count == 0 {
316 required_count = declarations.len();
317 }
318 let entries: Vec<DeclEntry> = declarations.values().cloned().collect();
319 if !is_shorthand || required_count < self.required_count {
320 if is_shorthand && declarations.has(shorthand) {
321 let mut cache: HashMap<u32, String> = HashMap::default();
322 let values = flatten(arena, &entries);
323 let mut is_important = false;
324 let mut filtered: Vec<u32> = Vec::new();
325 for &declaration in &values {
326 let dec = self.remove_defaults_of(arena, declaration, &mut cache);
327 for t in arena.token_iter(dec) {
328 let typ = arena.data_types.get(t);
329 if typ == EnumToken::ImportantTokenType {
330 is_important = true;
331 }
332 if filtered.is_empty() && typ != EnumToken::WhitespaceTokenType && typ != EnumToken::ImportantTokenType {
333 filtered.push(dec);
334 }
335 }
336 }
337 let defaults = str_list(&self.config["default"]);
338 if filtered.is_empty() && !defaults.is_empty() {
339 let parsed = self.parse(arena, defaults[0]);
340 filtered.push(arena.create_declaration(EnumToken::DeclarationNodeType, StrOrId::Str(shorthand), Some(&parsed), 0, None));
341 if is_important {
342 arena.append_token(filtered[0], arena.create_token(EnumToken::ImportantTokenType, TokenValue::None, None));
343 }
344 }
345 return if filtered.is_empty() { values } else { filtered };
346 }
347 for entry in &entries {
348 let DeclEntry::Node(declaration) = entry else {
349 continue;
350 };
351 let nam = arena.resolve_string(arena.name.get(*declaration));
352 let config = if nam == shorthand { self.config } else { non_null(properties_mapping.get(&*nam)).unwrap_or(self.config) };
353 let Some(mapping) = config.get("mapping") else {
354 continue;
355 };
356 let declaration_values = arena.tokens(*declaration);
357 for (key, val) in mapping.as_object().into_iter().flatten() {
358 let keys = self.parse(arena, key);
359 if keys.len() != declaration_values.len() {
360 continue;
361 }
362 if keys.iter().zip(&declaration_values).all(|(&k, &v)| eq_token(arena, k, v)) {
363 let parsed = self.parse(arena, val.as_str().unwrap_or(""));
364 arena.set_token_list(*declaration, &parsed);
365 break;
366 }
367 }
368 }
369 return flatten(arena, &entries);
370 }
371 let mut count = 0usize;
372 let separator = non_null(self.config.get("separator"));
373 let mut tokens: JsMap<Vec<Vec<u32>>> = JsMap::new();
374 for &(name, props) in &mapping_entries {
375 let Some(entry) = declarations.get(name).cloned() else {
376 continue;
377 };
378 let mut current = 0usize;
379 let decls = flatten(arena, &[entry]);
380 for declaration in decls {
381 for val in arena.token_iter(declaration) {
382 if match_config_token(arena, val, separator) {
383 current += 1;
384 if let Some(t) = tokens.get_mut(name) {
385 if t.len() == current {
386 t.push(Vec::new());
387 }
388 }
389 continue;
390 }
391 let val_type = arena.data_types.get(val);
392 if val_type == EnumToken::WhitespaceTokenType || val_type == EnumToken::CommentTokenType {
393 continue;
394 }
395 if truthy(props.get("multiple")) {
396 if let Some(sep) = non_null(props.get("separator")) {
397 if config_type(sep) == val_type
398 && (val_type == EnumToken::CommaTokenType
399 || sep.get("val").and_then(|v| v.as_str()).is_some_and(|v| arena.string_equals(arena.string_value.get(val), v)))
400 {
401 continue;
402 }
403 }
404 }
405 let matched = match_type(arena, val, props);
406 if is_shorthand {
407 is_shorthand = matched;
408 }
409 if self.property_names.get(&val).map(|n| &**n) == property || matched {
410 if !tokens.has(name) {
411 tokens.set(name, vec![Vec::new()]);
412 }
413 if let Some(group) = tokens.get_mut(name).unwrap().get_mut(current) {
415 group.push(val);
416 }
417 } else {
418 break;
419 }
420 }
421 }
422 if count == 0 {
423 count = current;
424 }
425 }
426 if shorthand == "grid-template" && patterns.len() == tokens.len() {
428 let first = |p: &str| tokens.get(p).and_then(|t| t.first()).cloned().unwrap_or_default();
429 let (t0, t1, t2) = (first(patterns[0]), first(patterns[1]), first(patterns.get(2).copied().unwrap_or("")));
430 let (k, l) = (t0.len(), t1.len());
431 let j = k.min(l);
432 let mut result: Vec<u32> = Vec::new();
433 for i in 0..j {
434 result.push(t0[i]);
435 result.push(t1[i]);
436 }
437 result.extend_from_slice(&t0[j..]);
438 result.extend_from_slice(&t1[j..]);
439 let prefix = non_null(self.config["properties"].get(patterns.get(2).copied().unwrap_or("")).and_then(|p| p.get("prefix")));
440 result.push(config_token(arena, prefix));
441 for (index, &t) in t2.iter().enumerate() {
442 if index > 0 {
443 result.push(arena.create_token(EnumToken::WhitespaceTokenType, TokenValue::None, None));
444 }
445 result.push(t);
446 }
447 let Some(DeclEntry::Node(source)) = declarations.get(patterns[0]).cloned() else {
448 return flatten(arena, &entries);
449 };
450 let declaration = arena.clone_node_deep(source, false, None);
451 arena.name.set(declaration, arena.intern_string(shorthand));
452 let taken: Vec<u32> = result.into_iter().map(|t| self.take(arena, t)).collect();
453 arena.set_token_list(declaration, &taken);
454 return vec![declaration];
455 }
456 count += 1;
457 let missing_required = mapping_entries.iter().any(|(name, cfg)| truthy(cfg.get("required")) && !tokens.has(name));
458 let counts_differ = !tokens.values().all(|v| {
459 v.iter().filter(|t| t.len() != 1 || arena.data_types.get(t[0]) != EnumToken::CommentTokenType).count() == count
460 });
461 if !is_shorthand || missing_required || counts_differ {
462 return flatten(arena, &entries);
463 }
464 if has_mapping {
465 if patterns.len() == tokens.len() {
466 let Some(DeclEntry::Node(source)) = declarations.get(patterns[0]).cloned() else {
467 return flatten(arena, &entries);
468 };
469 let declaration = arena.clone_node_deep(source, false, None);
470 let mut declaration_values = arena.tokens(declaration);
471 arena.name.set(declaration, arena.intern_string(shorthand));
472 for pattern in &patterns {
473 if !declaration_values.is_empty() {
474 declaration_values.push(config_token(arena, separator));
475 }
476 let groups = tokens.get(pattern).cloned().unwrap_or_default();
477 for (gi, group) in groups.iter().enumerate() {
478 if gi > 0 {
479 declaration_values.push(arena.create_token(EnumToken::WhitespaceTokenType, TokenValue::None, None));
480 }
481 for (ti, &t) in group.iter().enumerate() {
482 if ti > 0 {
483 declaration_values.push(arena.create_token(EnumToken::WhitespaceTokenType, TokenValue::None, None));
484 }
485 declaration_values.push(self.take(arena, t));
486 }
487 }
488 }
489 arena.set_token_list(declaration, &declaration_values);
490 return vec![declaration];
491 }
492 return flatten(arena, &entries);
493 }
494 let values = self.shorthand_values(arena, &tokens, required_count, separator);
495 vec![arena.create_declaration(EnumToken::DeclarationNodeType, StrOrId::Str(shorthand), Some(&values), 0, None)]
496 }
497
498 fn shorthand_values(&mut self, arena: &AstArena, tokens: &JsMap<Vec<Vec<u32>>>, required_count: usize, separator: Option<&Value>) -> Vec<u32> {
500 let properties_mapping = &self.config["properties"];
501 let global_properties = &get_config()["properties"];
502 let ws = |arena: &AstArena| arena.create_token(EnumToken::WhitespaceTokenType, TokenValue::None, None);
503 let mut acc: Vec<Vec<u32>> = Vec::new();
504 for (name, groups) in tokens.iter() {
505 let props = &properties_mapping[name];
506 let defaults = str_list(&props["default"]);
507 let required = truthy(props.get("required"));
508 for (i, group) in groups.iter().enumerate() {
509 if acc.len() == i {
510 acc.push(Vec::new());
511 }
512 let mut values: Vec<u32> = group.clone();
513 let rendered = group.iter().map(|&t| render_value_plain(arena, t) + " ").collect::<String>();
514 if defaults.contains(&rendered.trim_end()) && !required {
515 continue;
516 }
517 let mut do_filter_default = true;
519 if has_key(global_properties, name) {
520 for &v in &values {
521 let typ = arena.data_types.get(v);
522 if !matches!(typ, EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType | EnumToken::IdenTokenType)
523 || (typ == EnumToken::IdenTokenType && !defaults.contains(&&*arena.resolve_string(arena.string_value.get(v))))
524 {
525 do_filter_default = false;
526 break;
527 }
528 }
529 }
530 let filtered: Vec<u32> = values
531 .iter()
532 .copied()
533 .filter(|&val| {
534 let typ = arena.data_types.get(val);
535 if typ == EnumToken::WhitespaceTokenType || typ == EnumToken::CommentTokenType {
536 return false;
537 }
538 !do_filter_default || !(typ == EnumToken::IdenTokenType && defaults.contains(&&*arena.resolve_string(arena.string_value.get(val))))
539 })
540 .collect();
541 if !filtered.is_empty() || !(self.required_count == required_count && required) {
542 values = filtered;
543 }
544 if values.is_empty() {
545 continue;
546 }
547 if let Some(mapping) = props.get("mapping") {
548 let constraints = props.get("constraints");
549 let within = match constraints {
550 None => true,
551 Some(c) if !has_key(c, "max") => true,
552 Some(c) => c["mapping"]["max"].as_f64().is_some_and(|max| (values.len() as f64) <= max),
553 };
554 if within {
555 let mut k = values.len();
556 while k > 0 {
557 k -= 1;
558 if arena.data_types.get(values[k]) == EnumToken::IdenTokenType {
559 let key = arena.resolve_string(arena.string_value.get(values[k]));
560 if let Some(replacement) = mapping.get(&*key) {
561 let parsed = self.parse(arena, replacement.as_str().unwrap_or(""));
562 values.splice(k..k + 1, parsed);
563 }
564 }
565 }
566 }
567 }
568 if has_key(props, "prefix") {
569 acc[i].push(config_token(arena, props.get("prefix")));
570 } else if !acc[i].is_empty() {
571 acc[i].push(ws(arena));
572 }
573 let value_separator = non_null(props.get("separator"));
574 for (index, &v) in values.iter().enumerate() {
575 if index > 0 {
576 acc[i].push(config_token(arena, value_separator));
577 }
578 let taken = self.take(arena, v);
579 acc[i].push(taken);
580 }
581 }
582 }
583 let defaults = str_list(&self.config["default"]);
584 let mut values: Vec<u32> = Vec::new();
585 for mut curr in acc {
586 if !values.is_empty() {
587 values.push(config_token(arena, separator));
588 }
589 if curr.is_empty() && !defaults.is_empty() {
590 for (index, t) in self.parse(arena, defaults[0]).into_iter().enumerate() {
591 if index > 0 {
592 curr.push(ws(arena));
593 }
594 curr.push(t);
595 }
596 }
597 values.extend(curr);
598 }
599 if let Some(mapping) = non_null(self.config.get("mapping")) {
600 thread_local! {
601 static OPTIONS: ParserOptions = ParserOptions { remove_comments: Some(true), minify: Some(true), ..Default::default() };
602 }
603 let val: String = OPTIONS.with(|o| values.iter().map(|&t| render_value(arena, t, o)).collect());
604 if let Some(replacement) = mapping.get(&val) {
605 let typ = if val.starts_with('"') || val.starts_with('\'') { EnumToken::StringTokenType } else { EnumToken::IdenTokenType };
606 values = vec![arena.create_token(typ, TokenValue::Str(replacement.as_str().unwrap_or("")), None)];
607 }
608 }
609 if values.len() == 1 && arena.string_value.get(values[0]) != 0 {
610 let lower = arena.resolve_string(arena.string_value.get(values[0])).to_lowercase();
611 if defaults.contains(&lower.as_str()) && defaults.first() != Some(&lower.as_str()) {
612 values = self.parse(arena, defaults[0]);
613 }
614 }
615 values
616 }
617
618 pub fn take(&mut self, arena: &AstArena, token: u32) -> u32 {
620 if arena.parents.get(token) == 0 {
621 return token;
622 }
623 let clone = arena.clone_node_deep(token, true, None);
624 if let Some(name) = self.property_names.get(&token).cloned() {
625 self.property_names.insert(clone, name);
626 }
627 clone
628 }
629
630 fn match_types(&mut self, arena: &AstArena, declaration: u32) {
631 let patterns = self.pattern.clone();
632 let mut declaration_values = arena.tokens(declaration);
633 let mut values = declaration_values.clone();
634 let mut map: JsMap<f64> = JsMap::new();
636 for pattern in patterns.iter() {
637 let mut j: isize = 0;
638 while (j as usize) < values.len() {
639 if !map.has(pattern) {
640 let max = self.config["properties"].get(&**pattern).and_then(|p| p.get("constraints")).and_then(|c| c.get("mapping")).and_then(|m| m.get("max"));
641 map.set(pattern.clone(), non_null(max).and_then(|m| m.as_f64()).unwrap_or(1.0));
642 }
643 let count = *map.get(pattern).unwrap();
644 if count > 0.0 && match_type(arena, values[j as usize], self.props(pattern)) {
645 self.property_names.insert(values[j as usize], pattern.clone());
646 map.set(pattern.clone(), count - 1.0);
647 values.remove(j as usize);
648 j -= 1;
649 }
650 j += 1;
651 }
652 }
653 if let Some(set) = non_null(self.config.get("set")).and_then(|s| s.as_object()) {
654 let mut modified = false;
655 for (key, val) in set {
656 if !map.has(key) {
657 continue;
658 }
659 for v in str_list(val) {
660 if map.get(v) == Some(&1.0) {
662 let mut i = declaration_values.len();
663 while i > 0 {
664 i -= 1;
665 if self.property_names.get(&declaration_values[i]).map(|n| &**n) == Some(key.as_str()) {
666 let clone = arena.clone_node_deep(declaration_values[i], true, None);
667 self.property_names.insert(clone, Rc::from(v));
668 declaration_values.splice(i..i, [clone, arena.create_token(EnumToken::WhitespaceTokenType, TokenValue::None, None)]);
669 modified = true;
670 }
671 }
672 }
673 }
674 }
675 if modified {
676 arena.set_token_list(declaration, &declaration_values);
677 }
678 }
679 }
680
681 fn remove_defaults_of(&mut self, arena: &AstArena, declaration: u32, cache: &mut HashMap<u32, String>) -> u32 {
683 let sep = non_null(self.config.get("separator"));
684 let typ = match sep {
685 None => EnumToken::CommaTokenType,
686 Some(s) => config_type(s),
687 };
688 let separator: &str = match sep {
689 None => ",",
690 Some(s) => s.get("val").and_then(|v| v.as_str()).unwrap_or(""),
691 };
692 self.match_types(arena, declaration);
693 let mut map: JsMap<TokenMap> = JsMap::new();
694 let mut value: Vec<u32> = Vec::new();
695 let mut values: Vec<Vec<u32>> = Vec::new();
696 for t in arena.token_iter(declaration) {
697 let rendered = cache.entry(t).or_insert_with(|| render_value_minified(arena, t)).clone();
698 if arena.data_types.get(t) == typ && separator == rendered {
699 self.remove_defaults(arena, &map, &mut value);
700 values.push(std::mem::take(&mut value));
701 map.clear();
702 continue;
703 }
704 value.push(t);
705 if let Some(property_name) = self.property_names.get(&t).cloned() {
706 match map.get_mut(&property_name) {
707 None => map.set(property_name, TokenMap { t: vec![t], value: vec![rendered] }),
708 Some(v) => {
709 v.t.push(t);
710 v.value.push(rendered);
711 }
712 }
713 }
714 }
715 self.remove_defaults(arena, &map, &mut value);
716 values.push(value);
717 let mut result: Vec<u32> = Vec::new();
718 for curr in values {
719 if sep.is_some() && !result.is_empty() {
720 result.push(config_token(arena, sep));
721 }
722 for cr in curr {
723 if arena.data_types.get(cr) == EnumToken::WhitespaceTokenType && result.last().is_some_and(|&l| arena.data_types.get(l) == EnumToken::WhitespaceTokenType) {
724 continue;
725 }
726 result.push(cr);
727 }
728 }
729 while result.last().is_some_and(|&l| arena.data_types.get(l) == EnumToken::WhitespaceTokenType) {
730 result.pop();
731 }
732 while result.first().is_some_and(|&f| arena.data_types.get(f) == EnumToken::WhitespaceTokenType) {
733 result.remove(0);
734 }
735 arena.set_token_list(declaration, &result);
736 declaration
737 }
738
739 fn remove_defaults(&self, arena: &AstArena, map: &JsMap<TokenMap>, value: &mut Vec<u32>) {
740 let shorthand_defaults = str_list(&self.config["default"]);
741 for (key, val) in map.iter() {
742 let Some(config) = non_null(self.config["properties"].get(key)) else {
743 continue;
744 };
745 let v = val.value.join(" ");
746 let defaults = str_list(&config["default"]);
747 if !(defaults.contains(&v.as_str()) || (value.len() == 1 && shorthand_defaults.contains(&v.as_str()))) {
748 continue;
749 }
750 let prefix = non_null(config.get("prefix"));
751 let mut idx = 0usize;
753 while idx < value.len() {
754 let token = value[idx];
755 if val.t.contains(&token) {
756 let mut index = value.iter().position(|&x| x == token).unwrap();
757 value.remove(index);
758 if prefix.is_some() {
759 while index > 0 {
760 index -= 1;
761 if arena.data_types.get(value[index]) == EnumToken::WhitespaceTokenType {
762 continue;
763 }
764 if match_config_token(arena, value[index], prefix) {
765 value.remove(index);
766 break;
767 }
768 }
769 }
770 }
771 idx += 1;
772 }
773 }
774 }
775}
776
777fn render_value_plain(arena: &AstArena, token: u32) -> String {
779 crate::printer::render::render_value_default(arena, token)
780}
781
782fn render_value_minified(arena: &AstArena, token: u32) -> String {
784 thread_local! {
785 static OPTIONS: ParserOptions = ParserOptions { minify: Some(true), ..Default::default() };
786 }
787 OPTIONS.with(|o| render_value(arena, token, o))
788}