Skip to main content

rust_css_parser/printer/
render.rs

1//! Port of `src/printer/render.ts`.
2//!
3//! The rendered css is written to a utf-8 [`Writer`]. The typescript renderer memoizes identical declarations and
4//! constructs (`RenderMemo`): the rendering only depends on the token structure, the port renders them each time
5//! (same output).
6
7use crate::ast::arena::{AstArena, TokenField, TokenValue};
8use crate::ast::types::{ColorType, EnumAstNodeStatus, EnumToken};
9use crate::fs::resolve::{dirname, resolve};
10use crate::options::{ConvertColor, ParserOptions, SourceMapOption};
11use crate::parser::linesmap::LineMap;
12use crate::parser::source::SourceFile;
13use crate::parser::utils::angle::to_degrees;
14use crate::parser::utils::text::equals_ignore_case;
15use crate::printer::result::RenderResult;
16use crate::printer::sourcemap::SourceMap;
17use crate::printer::writer::{Writer, DEFAULT_CAPACITY};
18use crate::syntax::color::color::{convert_color, get_angle};
19use crate::syntax::color::hex::reduce_hex_value;
20use crate::syntax::constants::{anglePrecision, is_function_type, url_token_matcher, PSEUDO_ELEMENTS};
21use crate::syntax::syntax::{
22    is_white_space, minify_number, minify_number_str, parse_color, reduce_color_stops, reduce_conic_color_stops,
23    reducegradient_background_position, to_precision_angle, to_precision_value,
24};
25use crate::types::{ErrorDescription, SourceLocation};
26use crate::utils::number::{js_number_to_string, js_parse_number, to_fixed};
27use crate::utils::time::{format_ms, now};
28use crate::ast::cache::StructuralMemo;
29use std::cell::RefCell;
30use crate::utils::fx::HashMap;
31use std::rc::Rc;
32
33/// render options (`RenderOptions`): the parser options hold the render options
34pub type RenderOptions = ParserOptions;
35
36/// css modules mapping of a render (`:export` / `:import()`)
37#[derive(Clone, Debug, Default)]
38pub struct RenderMapping {
39    pub mapping: Vec<(String, String)>,
40    pub import_mapping: Option<Vec<(String, Vec<(String, String)>)>>,
41}
42
43/// rendered strings shared by the renderer (`RenderMemo`): identical declarations and identical constructs (colors,
44/// functions, parentheses, binary expressions, ...) are rendered once. a memo is only shared by renders that use the
45/// same options. the source map locations are not memoized: they are computed from the rendered string
46#[derive(Default)]
47pub struct RenderMemo {
48    /// rendered declarations (`name:value`), by name and value tokens
49    pub declarations: StructuralMemo<Rc<str>>,
50    /// rendered constructs: colors and tokens with sub tokens
51    pub constructs: StructuralMemo<Rc<str>>,
52    /// location of the declarations in the render buffer, by declaration slot: writer id, start, end, extra
53    locations: Vec<(u32, usize, usize, i64)>,
54    /// rendered values of the declarations (without the name), by declaration slot
55    values: Vec<Option<Rc<str>>>,
56}
57
58thread_local! {
59    /// cleared memos reused by the next renders
60    static FREE_MEMOS: RefCell<Vec<RenderMemo>> = const { RefCell::new(Vec::new()) };
61}
62
63impl RenderMemo {
64    /// a cleared memo
65    pub fn acquire() -> Self {
66        FREE_MEMOS.with(|f| f.borrow_mut().pop()).unwrap_or_default()
67    }
68
69    /// clear a memo that is no longer used and keep it for the next renders (4 memos at most)
70    pub fn release(mut memo: RenderMemo) {
71        FREE_MEMOS.with(|f| {
72            let mut free = f.borrow_mut();
73            if free.len() < 4 {
74                memo.declarations.clear();
75                memo.constructs.clear();
76                memo.values.clear();
77                // the writer ids are never reused: the locations are kept
78                free.push(memo);
79            }
80        });
81    }
82
83    /// record the location of a declaration in a render buffer
84    fn locate(&mut self, slot: usize, writer: &Writer, start: usize, extra: i64) {
85        if self.locations.len() <= slot {
86            self.locations.resize(slot + 1, (0, 0, 0, 0));
87        }
88        self.locations[slot] = (writer.id, start, writer.length(), writer.extra - extra);
89    }
90}
91
92/// render state shared by the nodes and the tokens of a render: the memo, valid for the options it was created for,
93/// and the resolved source file names of the source map
94pub struct RenderCache {
95    paths: RefCell<HashMap<String, String>>,
96    pub memo: RefCell<RenderMemo>,
97    /// the options the memo is valid for (identity, like `cache.options === options`)
98    options: *const RenderOptions,
99}
100
101impl RenderCache {
102    pub fn new(memo: RenderMemo, options: &RenderOptions) -> Self {
103        Self { paths: RefCell::new(HashMap::default()), memo: RefCell::new(memo), options }
104    }
105}
106
107/// the memo of the cache when the tokens are rendered with the options it was created for (`getRenderMemo()`)
108fn get_render_memo<'c>(cache: Option<&'c RenderCache>, options: &RenderOptions) -> Option<&'c RefCell<RenderMemo>> {
109    cache.filter(|c| std::ptr::eq(c.options, options)).map(|c| &c.memo)
110}
111
112/// a rendered string: a memoized string is shared, not copied
113pub enum Rendered {
114    Owned(String),
115    Shared(Rc<str>),
116}
117
118impl std::ops::Deref for Rendered {
119    type Target = str;
120    fn deref(&self) -> &str {
121        match self {
122            Rendered::Owned(s) => s,
123            Rendered::Shared(s) => s,
124        }
125    }
126}
127
128impl std::fmt::Display for Rendered {
129    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130        f.write_str(self)
131    }
132}
133
134impl From<Rendered> for String {
135    fn from(r: Rendered) -> String {
136        match r {
137            Rendered::Owned(s) => s,
138            Rendered::Shared(s) => s.to_string(),
139        }
140    }
141}
142
143/// source map records collected while rendering
144#[derive(Default)]
145struct SourceMapRecords {
146    sources: Vec<u32>,
147    maps: Vec<[i64; 5]>,
148}
149
150fn add_source(sourcemaps: &mut SourceMapRecords, src_id: u32) {
151    if !sourcemaps.sources.contains(&src_id) {
152        sourcemaps.sources.push(src_id);
153    }
154}
155
156/// copy of the options with the defaults of the missing options
157pub fn resolve_render_options(options: &RenderOptions) -> RenderOptions {
158    let minify = options.minify.unwrap_or(true);
159    let beautify = options.beautify.unwrap_or(!minify);
160    let mut o = options.clone();
161    o.indent.get_or_insert_with(|| if beautify { " ".into() } else { String::new() });
162    o.new_line.get_or_insert_with(|| if beautify { "\n".into() } else { String::new() });
163    o.remove_empty.get_or_insert(minify);
164    o.remove_comments.get_or_insert(minify);
165    if minify && o.minify.is_none() {
166        o.minify = Some(true);
167    }
168    o.minify_values.get_or_insert(true);
169    o.sourcemap.get_or_insert(SourceMapOption::Off);
170    o.convert_color.get_or_insert(ConvertColor::Bool(true));
171    o.expand_nesting_rules.get_or_insert(false);
172    o.preserve_license.get_or_insert(false);
173    o
174}
175
176/// token reducer: the comments are removed according to the options (`createReducer()`)
177pub struct Reducer<'a> {
178    pub options: &'a RenderOptions,
179    pub cache: Option<&'a RenderCache>,
180}
181
182impl<'a> Reducer<'a> {
183    pub fn new(options: &'a RenderOptions, cache: Option<&'a RenderCache>) -> Self {
184        Self { options, cache }
185    }
186
187    fn reduce(&self, arena: &AstArena, acc: &mut String, curr: u32) {
188        let o = self.options;
189        if arena.data_types.get(curr) == EnumToken::CommentTokenType && o.remove_comments == Some(true) {
190            if o.preserve_license != Some(true) || !arena.string_starts_with(arena.string_value.get(curr), "/*!") {
191                return;
192            }
193            acc.push_str(&arena.resolve_string(arena.string_value.get(curr)));
194            return;
195        }
196        if !render_simple_into(arena, curr, acc) {
197            acc.push_str(&render_value_with(arena, curr, o, self.cache, Some(self)));
198        }
199    }
200}
201
202/// append a token without children that renders its value as is (idents, strings, literals, separators, numbers): the
203/// value is written to the output, no string is created. false for the other tokens (see `render_token()`)
204fn render_simple_into(arena: &AstArena, token: u32, out: &mut String) -> bool {
205    if arena.first_token.get(token) != 0 || arena.first_child.get(token) != 0 {
206        return false;
207    }
208    match arena.data_types.get(token) {
209        EnumToken::CssTypeTokenType
210        | EnumToken::UrlTokenTokenType
211        | EnumToken::HashTokenType
212        | EnumToken::IdenTokenType
213        | EnumToken::StringTokenType
214        | EnumToken::LiteralTokenType
215        | EnumToken::UniCodeRange
216        | EnumToken::DashedIdenTokenType
217        | EnumToken::PseudoPageTokenType
218        | EnumToken::ClassSelectorTokenType => arena.with_string(arena.string_value.get(token), |v| out.push_str(v)),
219        EnumToken::NestingSelectorTokenType => out.push('&'),
220        EnumToken::DescendantCombinatorTokenType | EnumToken::WhitespaceTokenType => out.push(' '),
221        EnumToken::ColonTokenType => out.push(':'),
222        EnumToken::SemiColonTokenType => out.push(';'),
223        EnumToken::CommaTokenType => out.push(','),
224        // no fraction: no child
225        EnumToken::NumberTokenType => crate::syntax::syntax::with_minified_number(arena.numeric_value.get(token), |v| out.push_str(v)),
226        _ => return false,
227    }
228    true
229}
230
231/// renders nodes with the same options (`NodeRenderer`): the size of the rendered node
232pub struct NodeRenderer {
233    options: RenderOptions,
234    /// resolved options: boxed, the cache refers to them
235    resolved: Box<RenderOptions>,
236    /// render state: the memo keys contain interned string ids, the memo is valid for one arena
237    cache: RenderCache,
238    /// arena the cache is valid for
239    arena: *const AstArena,
240    direct: bool,
241    /// output buffer, reused by the renders: only the size of the output is read
242    writer: Writer,
243    indents: Vec<String>,
244}
245
246impl NodeRenderer {
247    pub fn new(options: &RenderOptions) -> Self {
248        let resolved = Box::new(resolve_render_options(options));
249        let direct = resolved.expand_nesting_rules != Some(true)
250            && resolved.with_parents != Some(true)
251            && matches!(resolved.sourcemap, None | Some(SourceMapOption::Off))
252            && resolved.output.is_none();
253        let cache = RenderCache::new(RenderMemo::default(), &resolved);
254        Self { options: options.clone(), resolved, cache, arena: std::ptr::null(), direct, writer: Writer::new(DEFAULT_CAPACITY), indents: Vec::new() }
255    }
256
257    /// rendered size of a node, in utf-16 code units
258    pub fn size(&mut self, arena: &AstArena, node: u32) -> usize {
259        if !std::ptr::eq(self.arena, arena) {
260            if !self.arena.is_null() {
261                self.cache = RenderCache::new(RenderMemo::default(), &self.resolved);
262            }
263            self.arena = arena;
264        }
265        if !self.direct {
266            let mut memo = self.cache.memo.borrow_mut();
267            return do_render_with(arena, node, &self.options, None, Some(&mut memo)).code_length;
268        }
269        let reducer = Reducer::new(&self.resolved, Some(&self.cache));
270        // the size is computed from the sizes of the parts: the node is not rendered
271        let (size, _) = node_size(arena, node, &self.resolved, &reducer, &self.cache, 0);
272        if size_check() {
273            self.writer.reset();
274            let mut location = SourceLocation::default();
275            render_ast_node(arena, node, &self.resolved, None, &mut location, None, &reducer, &self.cache, &mut self.writer, 0, &mut self.indents);
276            assert_eq!(size, self.writer.code_length(), "computed size of node {} differs from its rendered size", node);
277        }
278        size
279    }
280}
281
282/// `CSS_PARSER_CHECK_SIZE`: the computed sizes are checked against the rendered sizes (tests)
283fn size_check() -> bool {
284    use std::sync::OnceLock;
285    static CHECK: OnceLock<bool> = OnceLock::new();
286    *CHECK.get_or_init(|| std::env::var_os("CSS_PARSER_CHECK_SIZE").is_some())
287}
288
289const OUTPUT_PADDING: usize = 1 << 12;
290
291/// capacity of the buffer a node is rendered to
292pub fn output_capacity(arena: &AstArena, node: u32) -> usize {
293    let length = if arena.data_types.get(node) == EnumToken::StyleSheetNodeType {
294        arena.input_lengths.borrow().get(&node).copied().unwrap_or(0) as usize
295    } else if arena.flags.get(node) & EnumAstNodeStatus::HasLocation != 0 {
296        (arena.get_span_end(node) - arena.get_span_start(node)) as usize
297    } else {
298        0
299    };
300    if length > 0 {
301        length + OUTPUT_PADDING
302    } else {
303        DEFAULT_CAPACITY
304    }
305}
306
307/// render an ast (`doRender()`)
308pub fn do_render(arena: &AstArena, data: u32, options: &RenderOptions, mapping: Option<&RenderMapping>) -> RenderResult {
309    do_render_with(arena, data, options, mapping, None)
310}
311
312/// render an ast with the rendered values of a memo shared with other renders that use the same options (see
313/// [`NodeRenderer`]). without a memo, a memo is acquired and released
314pub fn do_render_with(arena: &AstArena, data: u32, options: &RenderOptions, mapping: Option<&RenderMapping>, memo: Option<&mut RenderMemo>) -> RenderResult {
315    let mut options = resolve_render_options(options);
316    let capacity = output_capacity(arena, data);
317    let mut data = data;
318    let expand_nesting = options.expand_nesting_rules == Some(true)
319        && matches!(arena.data_types.get(data), EnumToken::StyleSheetNodeType | EnumToken::AtRuleNodeType | EnumToken::RuleNodeType)
320        && arena.flags.get(data) & EnumAstNodeStatus::HasChildren != 0;
321    let mut sheet = 0u32;
322    if options.with_parents == Some(true) || expand_nesting {
323        let mut parent = arena.parents.get(data);
324        sheet = arena.create_style_sheet();
325        data = arena.clone_node_deep(data, true, None);
326        if options.with_parents == Some(true) {
327            while parent != 0 {
328                let clone = arena.clone_node_deep(parent, false, None);
329                arena.append_child(clone, data);
330                data = clone;
331                parent = arena.parents.get(parent);
332            }
333        }
334        arena.append_child(sheet, data);
335        if expand_nesting {
336            data = arena.expand(data);
337        }
338    }
339    let start_time = now();
340    let with_map = !matches!(options.sourcemap, None | Some(SourceMapOption::Off));
341    let mut sourcemaps = if with_map { Some(SourceMapRecords::default()) } else { None };
342    let mut source_location = SourceLocation::default();
343    let mut lines_map = if with_map { Some(LineMap::new(Vec::new())) } else { None };
344    let mut writer = Writer::new(capacity);
345    let indent = options.indent.clone().unwrap_or_default();
346    let new_line = options.new_line.clone().unwrap_or_default();
347    let cwd = options.cwd.clone().unwrap_or_default();
348    if let Some(mapping) = mapping {
349        let mut code = String::new();
350        if let Some(import_mapping) = &mapping.import_mapping {
351            let base = match &options.output {
352                Some(output) => dirname(output),
353                None => dirname(options.src.as_deref().unwrap_or("")),
354            };
355            let absolute_path = resolve(&base, &cwd, None).absolute;
356            for (key, value) in import_mapping {
357                let mut key = resolve(&resolve(key, &cwd, None).absolute, &absolute_path, None).relative;
358                if !key.starts_with('/') && !key.starts_with('.') {
359                    key = format!("./{}", key);
360                }
361                let body = value.iter().map(|(k, v)| format!("{}{}:{}{};", indent, v, indent, k)).collect::<Vec<_>>().join(&new_line);
362                code.push_str(&format!(":import(\"{}\"){}{{{}{}{}}}{}", key, indent, new_line, body, new_line, new_line));
363            }
364        }
365        let body = mapping.mapping.iter().map(|(k, v)| format!("{}{}:{}{};", indent, k, indent, v)).collect::<Vec<_>>().join(&new_line);
366        code.push_str(&format!(":export{}{{{}{}{}}}{}", indent, new_line, body, new_line, new_line));
367        writer.write(&code);
368        if let Some(lines_map) = lines_map.as_mut() {
369            move_location(&mut source_location, lines_map, &code, 0, None);
370        }
371    }
372    if let Some(output) = &options.output {
373        options.output = Some(resolve(output, &cwd, None).absolute);
374    }
375    // identical values are rendered once. the memo is valid for these options only
376    let own_memo = memo.is_none();
377    let mut memo = memo;
378    let initial = match memo.as_deref_mut() {
379        Some(m) => std::mem::take(m),
380        None => RenderMemo::acquire(),
381    };
382    let cache = RenderCache::new(initial, &options);
383    let reducer = Reducer::new(&options, Some(&cache));
384    let mut indents: Vec<String> = Vec::new();
385    render_ast_node(
386        arena,
387        data,
388        &options,
389        sourcemaps.as_mut(),
390        &mut source_location,
391        lines_map.as_mut(),
392        &reducer,
393        &cache,
394        &mut writer,
395        0,
396        &mut indents,
397    );
398    let total = format_ms(now() - start_time);
399    let used = cache.memo.replace(RenderMemo::default());
400    if own_memo {
401        RenderMemo::release(used);
402    } else if let Some(m) = memo {
403        *m = used;
404    }
405    if sheet != 0 {
406        arena.detach(data);
407    }
408    let mut map: Option<SourceMap> = None;
409    if let Some(records) = sourcemaps {
410        let mut sourcemap = SourceMap::new();
411        if let Some(sources) = &options.sources_map {
412            for &source_id in &records.sources {
413                if let Some(source) = sources.borrow().get(source_id) {
414                    let content = source.content.borrow().clone();
415                    sourcemap.add_source_content(source.id as i64, source.file.as_deref(), Some(&content));
416                }
417            }
418        }
419        let _ = sourcemap.add(&records.maps);
420        if options.sourcemap == Some(SourceMapOption::Inline) {
421            writer.write(&format!("\n/*# sourceMappingURL={} */", sourcemap.to_url()));
422        }
423        map = Some(sourcemap);
424    }
425    let code_length = writer.code_length();
426    RenderResult { bytes: writer.into_bytes(), errors: Vec::<ErrorDescription>::new(), total, map, code_length }
427}
428
429/// update the source map with the location of a node
430#[allow(clippy::too_many_arguments)]
431fn update_source_map(
432    arena: &AstArena,
433    node: u32,
434    options: &RenderOptions,
435    cache: &RenderCache,
436    sourcemaps: &mut SourceMapRecords,
437    source_location: &mut SourceLocation,
438    lines_map: &mut LineMap,
439    str: &str,
440) {
441    let offset = str.encode_utf16().take_while(|&u| is_white_space(u as u32)).count();
442    if offset > 0 {
443        move_location(source_location, lines_map, str, 0, Some(offset + 1));
444    }
445    if arena.flags.get(node) & EnumAstNodeStatus::HasLocation != 0 {
446        let mut src_id = arena.get_source(node);
447        let sources = options.sources_map.clone().unwrap_or_default();
448        let Some(source) = sources.borrow().get(src_id) else {
449            move_location(source_location, lines_map, str, offset, None);
450            return;
451        };
452        let input_source_map = source.get_input_source_map();
453        let (mut line, mut column) = source.line_starts.borrow().get_offsets(arena.get_span_start(node));
454        let generated_line = lines_map.search(source_location.end);
455        let new_line = generated_line + 1;
456        let new_column = source_location.end as i64 - lines_map.line_starts[generated_line.max(0) as usize] as i64 + if generated_line == 0 { 1 } else { 0 };
457        let records = input_source_map.and_then(|m| {
458            let mut m = (*m).clone();
459            m.find(line as i64, column as i64)
460        });
461        if let Some(records) = records {
462            for (file, l, c, content) in records {
463                let mut new_id: Option<u32> = None;
464                let mut source_file_name: Option<String> = file.as_deref().filter(|f| !f.is_empty()).map(String::from);
465                line = l as u32;
466                column = c as u32;
467                let source_content: Option<String> = content.as_deref().filter(|c| !c.is_empty()).map(String::from);
468                if let (Some(name), Some(output)) = (source_file_name.clone(), options.output.as_ref()) {
469                    if !name.starts_with("data:") {
470                        let cached = cache.paths.borrow().get(&name).cloned();
471                        let resolved = match cached {
472                            Some(p) => p,
473                            None => {
474                                let cwd = options.cwd.clone().unwrap_or_default();
475                                let absolute = resolve(&dirname(output), &cwd, None).absolute;
476                                let absolute_source_path = resolve(&dirname(options.src.as_deref().unwrap_or("")), &cwd, None).absolute;
477                                let absolute_source_file_name = resolve(&name, &absolute_source_path, None).absolute;
478                                let p = resolve(&absolute_source_file_name, &absolute, None).relative;
479                                cache.paths.borrow_mut().insert(name.clone(), p.clone());
480                                p
481                            }
482                        };
483                        source_file_name = Some(resolved);
484                    }
485                }
486                for (id, f) in sources.borrow().iter() {
487                    if f.file.as_deref() == source_file_name.as_deref() {
488                        new_id = Some(*id);
489                        break;
490                    }
491                    if source_file_name.is_none() && Some(&**f.content.borrow()) == source_content.as_deref() {
492                        new_id = Some(*id);
493                        break;
494                    }
495                }
496                let new_id = match new_id {
497                    Some(id) => id,
498                    None => {
499                        let s = SourceFile::new(Rc::from(source_content.as_deref().unwrap_or("")), Vec::new(), source_file_name.as_deref().map(Rc::from));
500                        sources.borrow_mut().insert(s.id, s.clone());
501                        s.id
502                    }
503                };
504                src_id = new_id;
505                add_source(sourcemaps, src_id);
506                sourcemaps.maps.push([new_line, new_column, src_id as i64, line as i64, column as i64]);
507            }
508        } else {
509            add_source(sourcemaps, src_id);
510            sourcemaps.maps.push([new_line, new_column, src_id as i64, line as i64, column as i64]);
511        }
512    }
513    move_location(source_location, lines_map, str, offset, None);
514}
515
516/// update the position (`move()`): the offsets are computed from the rendered string, its utf-16 code units are read
517/// in place (no copy)
518pub fn move_location(source_location: &mut SourceLocation, lines_map: &mut LineMap, str: &str, start: usize, end: Option<usize>) {
519    let end = end.unwrap_or(usize::MAX);
520    let mut units = str.encode_utf16().enumerate().peekable();
521    let mut previous: u16 = 0;
522    while let Some((i, unit)) = units.next() {
523        if i >= end {
524            break;
525        }
526        if i >= start {
527            source_location.end += 1;
528            let codepoint = unit as u32;
529            if matches!(codepoint, 0xa | 0xb | 0xc | 0xd | 0x2028 | 0x2029) {
530                let crlf_start = codepoint == 0xd && units.peek().is_some_and(|&(_, n)| n == 0xa);
531                let crlf_end = codepoint == 0xa && i > 0 && previous == 0xd;
532                if !crlf_start && !crlf_end {
533                    lines_map.line_starts.push(source_location.end);
534                }
535            }
536        }
537        previous = unit;
538    }
539    // `end` beyond the string: the missing code units are counted (`codepoint` is undefined in typescript)
540    let length = str.encode_utf16().count();
541    if end != usize::MAX && end > length {
542        source_location.end += (end - length.max(start)) as u32;
543    }
544}
545
546/// write an interned string (copied from the string table when ascii)
547fn write_string(arena: &AstArena, id: u32, writer: &mut Writer) {
548    if arena.string_length(id) == 0 {
549        return;
550    }
551    if arena.copy_string_ascii(id, &mut writer.buffer) < 0 {
552        writer.write(&arena.resolve_string(id));
553    }
554}
555
556/// render an ast node to the writer
557#[allow(clippy::too_many_arguments)]
558fn render_ast_node(
559    arena: &AstArena,
560    data: u32,
561    options: &RenderOptions,
562    mut sourcemaps: Option<&mut SourceMapRecords>,
563    source_location: &mut SourceLocation,
564    mut lines_map: Option<&mut LineMap>,
565    reducer: &Reducer,
566    cache: &RenderCache,
567    writer: &mut Writer,
568    level: usize,
569    indents: &mut Vec<String>,
570) {
571    let opt_indent = options.indent.clone().unwrap_or_default();
572    if indents.len() < level + 1 {
573        indents.push(opt_indent.repeat(level));
574    }
575    if indents.len() < level + 2 {
576        indents.push(opt_indent.repeat(level + 1));
577    }
578    let indent = indents[level].clone();
579    let typ = arena.data_types.get(data);
580    let new_line = options.new_line.clone().unwrap_or_default();
581    match typ {
582        EnumToken::DeclarationNodeType => {
583            write_string(arena, arena.name.get(data), writer);
584            writer.write_byte(0x3a);
585            writer.write(&opt_indent);
586            writer.write(&render_declaration_value(arena, data, options.minify_values == Some(true), reducer));
587        }
588        EnumToken::CommentNodeType | EnumToken::CDOCOMMNodeType => {
589            let id = arena.string_value.get(data);
590            if arena.string_starts_with(id, "/*# sourceMappingURL=") {
591                return;
592            }
593            if options.remove_comments != Some(true) || (options.preserve_license == Some(true) && arena.string_starts_with(id, "/*!")) {
594                write_string(arena, id, writer);
595            }
596        }
597        EnumToken::StyleSheetNodeType => {
598            let mut empty = true;
599            let mut node = arena.first_child.get(data);
600            while node != 0 {
601                let mark = writer.length();
602                let mark_extra = writer.extra;
603                if !empty && !new_line.is_empty() {
604                    writer.write(&new_line);
605                }
606                let start = writer.length();
607                render_ast_node(arena, node, options, sourcemaps.as_deref_mut(), source_location, lines_map.as_deref_mut(), reducer, cache, writer, level, indents);
608                if writer.length() == start {
609                    writer.truncate(mark, mark_extra);
610                    node = arena.next_sibling.get(node);
611                    continue;
612                }
613                empty = false;
614                if sourcemaps.is_some() && !new_line.is_empty() {
615                    move_location(source_location, lines_map.as_deref_mut().unwrap(), &new_line, 0, None);
616                }
617                node = arena.next_sibling.get(node);
618            }
619        }
620        EnumToken::AtRuleNodeType | EnumToken::RuleNodeType | EnumToken::KeyframesRuleNodeType | EnumToken::KeyframesAtRuleNodeType => {
621            let is_at_rule = typ == EnumToken::AtRuleNodeType || typ == EnumToken::KeyframesAtRuleNodeType;
622            let name_id = arena.name.get(data);
623            let value_id = arena.string_value.get(data);
624            let start = writer.length();
625            let start_extra = writer.extra;
626            if !indent.is_empty() && !new_line.is_empty() {
627                writer.write(&new_line);
628            }
629            if !indent.is_empty() {
630                writer.write(&indent);
631            }
632            if is_at_rule {
633                writer.write_byte(0x40);
634                write_string(arena, name_id, writer);
635                if arena.string_length(value_id) > 0 {
636                    writer.write(if opt_indent.is_empty() { " " } else { &opt_indent });
637                    write_string(arena, value_id, writer);
638                }
639                if arena.flags.get(data) & EnumAstNodeStatus::HasChildren == 0 {
640                    writer.write_byte(0x3b);
641                    return;
642                }
643            } else {
644                write_string(arena, name_id, writer);
645            }
646            if !opt_indent.is_empty() {
647                writer.write(&opt_indent);
648            }
649            writer.write_byte(0x7b);
650            let line_map_length = lines_map.as_ref().map_or(0, |l| l.line_starts.len());
651            let mut prelude = String::new();
652            if let Some(sm) = sourcemaps.as_deref_mut() {
653                let nam = arena.resolve_string(name_id);
654                let val = arena.resolve_string(value_id);
655                prelude = format!(
656                    "{}{}{}",
657                    if !indent.is_empty() { new_line.as_str() } else { "" },
658                    indent,
659                    if is_at_rule {
660                        format!("@{}{}{}{}{{", nam, if val.is_empty() { "" } else if opt_indent.is_empty() { " " } else { &opt_indent }, val, opt_indent)
661                    } else {
662                        format!("{}{}{{", nam, opt_indent)
663                    }
664                );
665                update_source_map(arena, data, options, cache, sm, source_location, lines_map.as_deref_mut().unwrap(), &prelude);
666            }
667            let indent_sub = indents[level + 1].clone();
668            let body = writer.length();
669            let record_declaration_source_map = typ == EnumToken::AtRuleNodeType;
670            let mut semicolon = false;
671            let mut node = arena.first_child.get(data);
672            while node != 0 {
673                let next = arena.next_sibling.get(node);
674                let node_type = arena.data_types.get(node);
675                if node_type == EnumToken::DeclarationNodeType && sourcemaps.is_none() {
676                    if semicolon {
677                        writer.write_byte(0x3b);
678                    }
679                    if !new_line.is_empty() {
680                        writer.write(&new_line);
681                    }
682                    if !indent_sub.is_empty() {
683                        writer.write(&indent_sub);
684                    }
685                    write_declaration(arena, node, options, cache, reducer, writer);
686                    semicolon = true;
687                    node = next;
688                    continue;
689                }
690                let str: String;
691                if node_type == EnumToken::CommentNodeType {
692                    let comment_id = arena.string_value.get(node);
693                    if options.remove_comments == Some(true) && (options.preserve_license != Some(true) || !arena.string_starts_with(comment_id, "/*!")) {
694                        node = next;
695                        continue;
696                    }
697                    str = arena.resolve_string(comment_id).to_string();
698                } else if node_type == EnumToken::DeclarationNodeType {
699                    str = render_declaration(arena, node, options, cache, reducer).into();
700                } else {
701                    let mark = writer.length();
702                    if semicolon {
703                        writer.write_byte(0x3b);
704                    }
705                    let child_start = writer.length();
706                    render_ast_node(arena, node, options, sourcemaps.as_deref_mut(), source_location, lines_map.as_deref_mut(), reducer, cache, writer, level + 1, indents);
707                    if writer.length() == child_start {
708                        writer.buffer.truncate(mark);
709                        node = next;
710                        continue;
711                    }
712                    semicolon = ends_with_semicolon(arena, node, writer);
713                    if semicolon {
714                        writer.buffer.pop();
715                    }
716                    node = next;
717                    continue;
718                }
719                if str.is_empty() {
720                    node = next;
721                    continue;
722                }
723                if semicolon {
724                    writer.write_byte(0x3b);
725                }
726                let written: String;
727                if sourcemaps.is_none() {
728                    if !new_line.is_empty() {
729                        writer.write(&new_line);
730                    }
731                    if !indent_sub.is_empty() {
732                        writer.write(&indent_sub);
733                    }
734                    writer.write(&str);
735                    written = str;
736                } else {
737                    written = format!("{}{}{}", new_line, indent_sub, str);
738                    writer.write(&written);
739                }
740                if node_type == EnumToken::DeclarationNodeType {
741                    semicolon = true;
742                } else {
743                    semicolon = writer.last_byte() == 0x3b;
744                    if semicolon {
745                        writer.buffer.pop();
746                    }
747                }
748                if let Some(sm) = sourcemaps.as_deref_mut() {
749                    if node_type == EnumToken::DeclarationNodeType && record_declaration_source_map {
750                        update_source_map(arena, node, options, cache, sm, source_location, lines_map.as_deref_mut().unwrap(), &written);
751                    } else {
752                        move_location(source_location, lines_map.as_deref_mut().unwrap(), &written, 0, None);
753                    }
754                    if node_type == EnumToken::DeclarationNodeType {
755                        source_location.end += 1;
756                    }
757                }
758                node = next;
759            }
760            if semicolon {
761                source_location.end = source_location.end.saturating_sub(1);
762            }
763            if options.remove_empty == Some(true)
764                && writer.length() == body
765                && !(typ == EnumToken::AtRuleNodeType
766                    && (arena.string_equals(name_id, "apply") || arena.string_equals(name_id, "mixin") || arena.string_equals(name_id, "function")))
767            {
768                if sourcemaps.is_some() {
769                    source_location.end = source_location.end.saturating_sub(prelude.encode_utf16().count() as u32);
770                    if let Some(l) = lines_map.as_deref_mut() {
771                        l.line_starts.truncate(line_map_length);
772                    }
773                }
774                writer.truncate(start, start_extra);
775                return;
776            }
777            if !new_line.is_empty() {
778                writer.write(&new_line);
779            }
780            if !indent.is_empty() {
781                writer.write(&indent);
782            }
783            writer.write_byte(0x7d);
784            if sourcemaps.is_some() {
785                move_location(source_location, lines_map.as_deref_mut().unwrap(), &format!("{}{}}}", new_line, indent), 0, None);
786            }
787        }
788        _ => {}
789    }
790}
791
792/// true if a rendered child node ends with a semicolon
793fn ends_with_semicolon(arena: &AstArena, node: u32, writer: &Writer) -> bool {
794    match arena.data_types.get(node) {
795        EnumToken::AtRuleNodeType | EnumToken::KeyframesAtRuleNodeType => arena.flags.get(node) & EnumAstNodeStatus::HasChildren == 0,
796        EnumToken::RuleNodeType | EnumToken::KeyframesRuleNodeType => false,
797        _ => writer.last_byte() == 0x3b,
798    }
799}
800
801/// the values of the custom properties and of `initial-value` are not minified
802fn is_unminified_declaration(arena: &AstArena, node: u32) -> bool {
803    arena.starts_with(node, "nam", "--") || arena.string_equals(arena.name.get(node), "initial-value")
804}
805
806/// render a declaration: `name:value`, without the semicolon
807/// render a declaration without memoization: `name:value`, without the semicolon
808fn render_declaration_string(arena: &AstArena, node: u32, options: &RenderOptions, cache: &RenderCache, reducer: &Reducer) -> String {
809    let unminified;
810    let own_reducer;
811    let (options, reducer) = if options.minify_values == Some(true) && is_unminified_declaration(arena, node) {
812        // the values of the custom properties are not minified
813        unminified = RenderOptions { minify_values: Some(false), ..options.clone() };
814        own_reducer = Reducer::new(&unminified, Some(cache));
815        (&unminified, &own_reducer)
816    } else {
817        (options, reducer)
818    };
819    format!(
820        "{}:{}{}",
821        arena.resolve_string(arena.name.get(node)),
822        options.indent.as_deref().unwrap_or(""),
823        render_declaration_value(arena, node, options.minify_values == Some(true), reducer).trim_end()
824    )
825}
826
827/// render a declaration of a block: `name:value`, without the semicolon. identical declarations (same name, same
828/// value tokens) are rendered once per render
829fn render_declaration(arena: &AstArena, node: u32, options: &RenderOptions, cache: &RenderCache, reducer: &Reducer) -> Rendered {
830    let Some(memo) = get_render_memo(Some(cache), options) else {
831        return Rendered::Owned(render_declaration_string(arena, node, options, cache, reducer));
832    };
833    // the name is part of the key
834    let slot = memo.borrow_mut().declarations.list(arena, arena.first_token.get(node), arena.name.get(node) as i32);
835    if let Some(rendered) = memo.borrow().declarations.get(slot) {
836        return Rendered::Shared(rendered.clone());
837    }
838    let rendered: Rc<str> = Rc::from(render_declaration_string(arena, node, options, cache, reducer));
839    memo.borrow_mut().declarations.set(slot, rendered.clone());
840    Rendered::Shared(rendered)
841}
842
843/// write a declaration of a block: `name:value`, without the semicolon. identical declarations are rendered and
844/// encoded once per render: the bytes written first are copied
845/// the rendered value of a declaration (without the name): rendered once per structure, see [`RenderMemo`]. returns
846/// the memo slot (`usize::MAX` without memo) and the value
847fn declaration_value(arena: &AstArena, node: u32, options: &RenderOptions, cache: &RenderCache, reducer: &Reducer) -> (usize, Rc<str>) {
848    declaration_value_at(arena, node, options, cache, reducer, None)
849}
850
851/// see [`declaration_value`]: `slot` is the memo slot of the declaration when it has been looked up (one lookup per
852/// declaration)
853fn declaration_value_at(arena: &AstArena, node: u32, options: &RenderOptions, cache: &RenderCache, reducer: &Reducer, slot: Option<usize>) -> (usize, Rc<str>) {
854    let memo = get_render_memo(Some(cache), options);
855    let mut slot = slot.unwrap_or(usize::MAX);
856    if let Some(memo) = memo {
857        // the name is part of the key
858        if slot == usize::MAX {
859            slot = memo.borrow_mut().declarations.list(arena, arena.first_token.get(node), arena.name.get(node) as i32);
860        }
861        if let Some(value) = memo.borrow().values.get(slot).cloned().flatten() {
862            return (slot, value);
863        }
864    }
865    let value = if options.minify_values == Some(true) && is_unminified_declaration(arena, node) {
866        let unminified = RenderOptions { minify_values: Some(false), ..options.clone() };
867        let own = Reducer::new(&unminified, Some(cache));
868        render_declaration_value(arena, node, false, &own)
869    } else {
870        render_declaration_value(arena, node, options.minify_values == Some(true), reducer)
871    };
872    let value: Rc<str> = Rc::from(value.trim_end());
873    if let Some(memo) = memo {
874        let mut m = memo.borrow_mut();
875        if m.values.len() <= slot {
876            m.values.resize(slot + 1, None);
877        }
878        m.values[slot] = Some(value.clone());
879    }
880    (slot, value)
881}
882
883fn write_declaration(arena: &AstArena, node: u32, options: &RenderOptions, cache: &RenderCache, reducer: &Reducer, writer: &mut Writer) {
884    let memo = get_render_memo(Some(cache), options);
885    let mut looked_up = None;
886    if let Some(memo) = memo {
887        // an identical declaration is already written to the buffer: its bytes are copied
888        let slot = memo.borrow_mut().declarations.list(arena, arena.first_token.get(node), arena.name.get(node) as i32);
889        let location = memo.borrow().locations.get(slot).copied();
890        if let Some((id, start, end, extra)) = location {
891            if id == writer.id {
892                writer.copy(start, end, extra);
893                return;
894            }
895        }
896        looked_up = Some(slot);
897    }
898    let start = writer.length();
899    let extra = writer.extra;
900    let (slot, value) = declaration_value_at(arena, node, options, cache, reducer, looked_up);
901    // the parts are written directly: the name is copied from the string table
902    write_string(arena, arena.name.get(node), writer);
903    writer.write_byte(0x3a);
904    if let Some(indent) = options.indent.as_deref().filter(|i| !i.is_empty()) {
905        writer.write(indent);
906    }
907    writer.write(&value);
908    if let Some(memo) = memo {
909        memo.borrow_mut().locate(slot, writer, start, extra);
910    }
911}
912
913/// length of a string in utf-16 code units (`string.length`)
914fn units(s: &str) -> usize {
915    if s.is_ascii() {
916        s.len()
917    } else {
918        s.encode_utf16().count()
919    }
920}
921
922/// the size of a rendered node, computed without rendering it: the declarations are measured from their rendered
923/// values (rendered once per structure, see [`declaration_value`]), the layout follows [`render_ast_node`] (no source
924/// map). returns the size in utf-16 code units (0 when the node renders nothing) and whether the output ends with a
925/// semicolon
926fn node_size(arena: &AstArena, data: u32, options: &RenderOptions, reducer: &Reducer, cache: &RenderCache, level: usize) -> (usize, bool) {
927    let opt_indent = options.indent.as_deref().unwrap_or("");
928    let new_line = options.new_line.as_deref().unwrap_or("");
929    let indent_len = units(opt_indent) * level;
930    let new_line_len = units(new_line);
931    let typ = arena.data_types.get(data);
932    match typ {
933        EnumToken::DeclarationNodeType => {
934            let (_, value) = declaration_value(arena, data, options, cache, reducer);
935            let size = arena.string_length(arena.name.get(data)) + 1 + units(opt_indent) + units(&value);
936            (size, value.ends_with(';'))
937        }
938        EnumToken::CommentNodeType | EnumToken::CDOCOMMNodeType => {
939            let id = arena.string_value.get(data);
940            if arena.string_starts_with(id, "/*# sourceMappingURL=") {
941                return (0, false);
942            }
943            if options.remove_comments != Some(true) || (options.preserve_license == Some(true) && arena.string_starts_with(id, "/*!")) {
944                let length = arena.string_length(id);
945                return (length, length > 0 && arena.with_string(id, |s| s.ends_with(';')));
946            }
947            (0, false)
948        }
949        EnumToken::StyleSheetNodeType => {
950            let mut size = 0;
951            let mut empty = true;
952            let mut last_semicolon = false;
953            let mut node = arena.first_child.get(data);
954            while node != 0 {
955                let (child, semicolon) = node_size(arena, node, options, reducer, cache, level);
956                if child > 0 {
957                    if !empty {
958                        size += new_line_len;
959                    }
960                    size += child;
961                    empty = false;
962                    last_semicolon = semicolon;
963                }
964                node = arena.next_sibling.get(node);
965            }
966            (size, last_semicolon)
967        }
968        EnumToken::AtRuleNodeType | EnumToken::RuleNodeType | EnumToken::KeyframesRuleNodeType | EnumToken::KeyframesAtRuleNodeType => {
969            let is_at_rule = typ == EnumToken::AtRuleNodeType || typ == EnumToken::KeyframesAtRuleNodeType;
970            let name_id = arena.name.get(data);
971            let value_id = arena.string_value.get(data);
972            let mut size = 0;
973            if indent_len > 0 && new_line_len > 0 {
974                size += new_line_len;
975            }
976            size += indent_len;
977            if is_at_rule {
978                size += 1 + arena.string_length(name_id);
979                if arena.string_length(value_id) > 0 {
980                    size += if opt_indent.is_empty() { 1 } else { units(opt_indent) } + arena.string_length(value_id);
981                }
982                if arena.flags.get(data) & EnumAstNodeStatus::HasChildren == 0 {
983                    return (size + 1, true);
984                }
985            } else {
986                size += arena.string_length(name_id);
987            }
988            size += units(opt_indent) + 1;
989            let indent_sub_len = units(opt_indent) * (level + 1);
990            let mut body = 0;
991            let mut semicolon = false;
992            let mut node = arena.first_child.get(data);
993            while node != 0 {
994                let next = arena.next_sibling.get(node);
995                let node_type = arena.data_types.get(node);
996                if node_type == EnumToken::DeclarationNodeType {
997                    let (declaration, _) = node_size(arena, node, options, reducer, cache, level + 1);
998                    body += semicolon as usize + new_line_len + indent_sub_len + declaration;
999                    semicolon = true;
1000                } else if node_type == EnumToken::CommentNodeType {
1001                    let comment_id = arena.string_value.get(node);
1002                    if !(options.remove_comments == Some(true) && (options.preserve_license != Some(true) || !arena.string_starts_with(comment_id, "/*!"))) {
1003                        let length = arena.string_length(comment_id);
1004                        if length > 0 {
1005                            body += semicolon as usize + new_line_len + indent_sub_len + length;
1006                            // a trailing semicolon is removed: it is written before the next node
1007                            semicolon = arena.with_string(comment_id, |s| s.ends_with(';'));
1008                            if semicolon {
1009                                body -= 1;
1010                            }
1011                        }
1012                    }
1013                } else {
1014                    let (child, ends_with) = node_size(arena, node, options, reducer, cache, level + 1);
1015                    if child > 0 {
1016                        body += semicolon as usize + child;
1017                        semicolon = match node_type {
1018                            EnumToken::AtRuleNodeType | EnumToken::KeyframesAtRuleNodeType => arena.flags.get(node) & EnumAstNodeStatus::HasChildren == 0,
1019                            EnumToken::RuleNodeType | EnumToken::KeyframesRuleNodeType => false,
1020                            _ => ends_with,
1021                        };
1022                        if semicolon {
1023                            body -= 1;
1024                        }
1025                    }
1026                }
1027                node = next;
1028            }
1029            if options.remove_empty == Some(true)
1030                && body == 0
1031                && !(typ == EnumToken::AtRuleNodeType
1032                    && (arena.string_equals(name_id, "apply") || arena.string_equals(name_id, "mixin") || arena.string_equals(name_id, "function")))
1033            {
1034                return (0, false);
1035            }
1036            (size + body + new_line_len + indent_len + 1, false)
1037        }
1038        _ => (0, false),
1039    }
1040}
1041
1042thread_local! {
1043    /// number of declaration values rendered, see [`declaration_renders`]
1044    static DECLARATION_RENDERS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1045}
1046
1047/// number of declaration values rendered on this thread: an identical declaration is rendered once per render
1048pub fn declaration_renders() -> usize {
1049    DECLARATION_RENDERS.with(|c| c.get())
1050}
1051
1052/// render the value tokens of a declaration with the reducer. with `minify_values`, the whitespace before
1053/// `!important` and after a function is dropped
1054pub fn render_declaration_value(arena: &AstArena, node: u32, minify_values: bool, reducer: &Reducer) -> String {
1055    DECLARATION_RENDERS.with(|c| c.set(c.get() + 1));
1056    let mut rendered = String::new();
1057    let mut token = arena.first_token.get(node);
1058    if !minify_values {
1059        while token != 0 {
1060            reducer.reduce(arena, &mut rendered, token);
1061            token = arena.next_sibling.get(token);
1062        }
1063        return rendered;
1064    }
1065    let t = |x: u32| arena.data_types.get(x);
1066    let mut pending = 0u32;
1067    let mut check = true;
1068    let mut drop_whitespace = false;
1069    while token != 0 {
1070        let typ = t(token);
1071        if drop_whitespace {
1072            drop_whitespace = false;
1073            if typ == EnumToken::WhitespaceTokenType {
1074                token = arena.next_sibling.get(token);
1075                continue;
1076            }
1077        }
1078        if !check {
1079            check = true;
1080        } else if typ == EnumToken::ImportantTokenType && pending != 0 && t(pending) == EnumToken::WhitespaceTokenType {
1081            pending = 0;
1082            check = false;
1083        } else if is_function_type(typ)
1084            && (typ != EnumToken::ColorTokenType || arena.first_token.get(token) != 0)
1085            && typ != EnumToken::WildCardFunctionTokenType
1086            && arena.next_sibling.get(token) != 0
1087            && t(arena.next_sibling.get(token)) == EnumToken::WhitespaceTokenType
1088        {
1089            drop_whitespace = true;
1090        }
1091        if pending != 0 {
1092            reducer.reduce(arena, &mut rendered, pending);
1093        }
1094        pending = token;
1095        token = arena.next_sibling.get(token);
1096    }
1097    if pending != 0 {
1098        reducer.reduce(arena, &mut rendered, pending);
1099    }
1100    rendered
1101}
1102
1103/// render the tokens of a linked list with the reducer, or with the comment rules of the options
1104fn render_reduced(arena: &AstArena, first: u32, options: &RenderOptions, cache: Option<&RenderCache>, reducer: Option<&Reducer>) -> String {
1105    let mut result = String::new();
1106    let mut token = first;
1107    while token != 0 {
1108        if let Some(reducer) = reducer {
1109            reducer.reduce(arena, &mut result, token);
1110        } else if arena.data_types.get(token) == EnumToken::CommentTokenType && options.remove_comments == Some(true) {
1111            if options.preserve_license == Some(true) && arena.string_starts_with(arena.string_value.get(token), "/*!") {
1112                result.push_str(&arena.resolve_string(arena.string_value.get(token)));
1113            }
1114        } else if !render_simple_into(arena, token, &mut result) {
1115            result.push_str(&render_value_with(arena, token, options, cache, None));
1116        }
1117        token = arena.next_sibling.get(token);
1118    }
1119    result
1120}
1121
1122/// render the tokens of a linked list
1123fn render_list(arena: &AstArena, first: u32, options: &RenderOptions, cache: Option<&RenderCache>, reducer: Option<&Reducer>) -> String {
1124    let mut result = String::new();
1125    let mut token = first;
1126    while token != 0 {
1127        if !render_simple_into(arena, token, &mut result) {
1128            result.push_str(&render_value_with(arena, token, options, cache, reducer));
1129        }
1130        token = arena.next_sibling.get(token);
1131    }
1132    result
1133}
1134
1135/// render the tokens of a field of a structured token
1136fn render_field(arena: &AstArena, token: u32, field: u32, options: &RenderOptions, cache: Option<&RenderCache>, reducer: Option<&Reducer>) -> String {
1137    match arena.get_child_at(token, field) {
1138        None => String::new(),
1139        Some(list) => render_list(arena, arena.first_token.get(list), options, cache, reducer),
1140    }
1141}
1142
1143fn is_legacy_color_function(name: &str) -> bool {
1144    matches!(name, "rgb" | "rgba" | "hsl" | "hsla")
1145}
1146
1147fn is_alpha_color_function(name: &str) -> bool {
1148    matches!(name, "rgb" | "rgba" | "hsl" | "hsla" | "hwb" | "oklab" | "oklch" | "lab" | "lch")
1149}
1150
1151/// `/[,/]\s*$/`
1152fn has_trailing_separator(s: &str) -> bool {
1153    s.trim_end_matches(crate::ast::arena::is_js_whitespace).ends_with([',', '/'])
1154}
1155
1156/// the color type a color is converted to
1157fn convert_target(options: &RenderOptions) -> u8 {
1158    match options.convert_color {
1159        None | Some(ConvertColor::Bool(_)) => {
1160            if matches!(options.convert_color, Some(ConvertColor::Bool(_))) {
1161                ColorType::HEX
1162            } else {
1163                // `ColorType[options.convertColor ?? "HEX"]` -> the name "HEX" is not a number: `ColorType["HEX"]` = 3
1164                ColorType::value(ColorType::name(ColorType::HEX).unwrap_or("HEX")).unwrap_or(ColorType::HEX)
1165            }
1166        }
1167        Some(ConvertColor::Type(t)) => ColorType::name(t)
1168            .map(|n| n.to_uppercase().replace('-', "_"))
1169            .and_then(|n| ColorType::value(&n))
1170            .unwrap_or(ColorType::HEX),
1171    }
1172}
1173
1174/// render a color token
1175fn render_color(arena: &AstArena, token: u32, options: &RenderOptions, cache: Option<&RenderCache>, reducer: Option<&Reducer>) -> String {
1176    let mut token = token;
1177    if options.convert_color != Some(ConvertColor::Bool(false)) {
1178        if let Some(value) = convert_color(arena, token, convert_target(options)) {
1179            token = value;
1180        }
1181        if matches!(arena.color_type.get(token), ColorType::HEX | ColorType::LIT) {
1182            return reduce_hex_value(&arena.resolve_string(arena.string_value.get(token)));
1183        }
1184    }
1185    let kin = arena.color_type.get(token);
1186    if matches!(kin, ColorType::SYS | ColorType::DPSYS | ColorType::NON_STD | ColorType::HEX | ColorType::LIT) {
1187        return arena.resolve_string(arena.string_value.get(token)).to_string();
1188    }
1189    if arena.first_token.get(token) == 0 {
1190        return format!("{}({})", arena.resolve_string(arena.string_value.get(token)), render_reduced(arena, 0, options, cache, reducer));
1191    }
1192    let fn_name = arena.resolve_string(arena.string_value.get(token));
1193    let count = arena.token_count(token) as usize;
1194    let is_legacy = is_legacy_color_function(&fn_name);
1195    let has_alpha = is_alpha_color_function(&fn_name);
1196    let use_alpha = (has_alpha && count == if is_legacy { 7 } else { 4 }) || (fn_name == "color" && count == 5);
1197    let mut result = String::new();
1198    let t = |x: u32| arena.data_types.get(x);
1199    for (index, curr) in arena.token_iter(token).enumerate() {
1200        if has_trailing_separator(&result) {
1201            if t(curr) == EnumToken::WhitespaceTokenType {
1202                result = result.trim_end().to_string();
1203                continue;
1204            }
1205            result = format!("{}{}", result.trim_start(), render_value_with(arena, curr, options, cache, None));
1206            continue;
1207        }
1208        if (is_legacy && t(curr) == EnumToken::CommaTokenType) || t(curr) == EnumToken::WhitespaceTokenType {
1209            result = format!("{} ", result.trim_end());
1210        } else if t(curr) == EnumToken::CommaTokenType || (t(curr) == EnumToken::LiteralTokenType && arena.string_equals(arena.string_value.get(curr), "/")) {
1211            result = format!("{}{}", result.trim_end(), if t(curr) == EnumToken::CommaTokenType { "," } else { "/" });
1212        } else {
1213            let sep = if use_alpha && index == count - 1 { "/" } else { " " };
1214            result = format!("{}{}{}", result.trim_end(), sep, render_value_with(arena, curr, options, cache, None));
1215        }
1216    }
1217    let name = if has_alpha && fn_name.ends_with('a') { &fn_name[..fn_name.len() - 1] } else { fn_name.as_str() };
1218    format!("{}({})", name, result.trim_start())
1219}
1220
1221/// render a token with the options (`renderValue()`)
1222pub fn render_value(arena: &AstArena, token: u32, options: &RenderOptions) -> String {
1223    render_value_with(arena, token, options, None, None).into()
1224}
1225
1226/// render a token with the default options
1227pub fn render_value_default(arena: &AstArena, token: u32) -> String {
1228    thread_local! {
1229        static DEFAULT: RenderOptions = RenderOptions::default();
1230    }
1231    DEFAULT.with(|options| render_value_with(arena, token, options, None, None).into())
1232}
1233
1234/// render a token. identical constructs (colors and tokens with sub tokens: functions, parentheses, binary
1235/// expressions, ...) are rendered once per render, see [`RenderMemo`]
1236pub fn render_value_with(arena: &AstArena, token: u32, options: &RenderOptions, cache: Option<&RenderCache>, reducer: Option<&Reducer>) -> Rendered {
1237    if arena.data_types.get(token) == EnumToken::ColorTokenType || arena.first_token.get(token) != 0 || arena.first_child.get(token) != 0 {
1238        if let Some(memo) = get_render_memo(cache, options) {
1239            let slot = memo.borrow_mut().constructs.token(arena, token);
1240            if let Some(rendered) = memo.borrow().constructs.get(slot) {
1241                return Rendered::Shared(rendered.clone());
1242            }
1243            let rendered: Rc<str> = Rc::from(render_token(arena, token, options, cache, reducer));
1244            memo.borrow_mut().constructs.set(slot, rendered.clone());
1245            return Rendered::Shared(rendered);
1246        }
1247    }
1248    Rendered::Owned(render_token(arena, token, options, cache, reducer))
1249}
1250
1251/// `minifyNumber(String(n))`
1252fn minify_str(v: &str) -> String {
1253    minify_number_str(v)
1254}
1255
1256fn is_ws_or_comment(arena: &AstArena, t: Option<u32>) -> bool {
1257    t.is_some_and(|t| matches!(arena.data_types.get(t), EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType))
1258}
1259
1260fn str_eq(arena: &AstArena, t: Option<u32>, s: &str) -> bool {
1261    t.is_some_and(|t| arena.with_string(arena.string_value.get(t), |v| equals_ignore_case(v, s)))
1262}
1263
1264fn typ_of(arena: &AstArena, t: Option<u32>) -> u8 {
1265    t.map_or(0, |t| arena.data_types.get(t))
1266}
1267
1268/// minify the arguments of a gradient (`linear-gradient`, `radial-gradient`, `conic-gradient`)
1269fn minify_gradient(arena: &AstArena, token: u32, slice: &mut Vec<u32>) {
1270    let name = arena.resolve_string(arena.string_value.get(token));
1271    let at = |slice: &Vec<u32>, i: usize| slice.get(i).copied();
1272    let ws = |_: u32| arena.create_token(EnumToken::WhitespaceTokenType, TokenValue::None, None);
1273    match &*name {
1274        "linear-gradient" | "repeating-linear-gradient" => {
1275            let mut i: isize = 0;
1276            while (i as usize) < slice.len() {
1277                let iu = i as usize;
1278                let ti = typ_of(arena, at(slice, iu));
1279                if ti == EnumToken::ColorTokenType || ti == EnumToken::CommaTokenType {
1280                    break;
1281                }
1282                if ti == EnumToken::IdenTokenType && str_eq(arena, at(slice, iu), "to") {
1283                    let mut k = iu + 1;
1284                    while k < slice.len() && is_ws_or_comment(arena, at(slice, k)) {
1285                        k += 1;
1286                    }
1287                    if k < slice.len() && typ_of(arena, at(slice, k)) == EnumToken::IdenTokenType {
1288                        let key = arena.resolve_string(arena.string_value.get(slice[k])).to_lowercase();
1289                        match key.as_str() {
1290                            "right" => {
1291                                let angle = arena.create_token(EnumToken::AngleTokenType, TokenValue::Num(90.0), Some("deg"));
1292                                slice.splice(iu..k + 1, [angle]);
1293                            }
1294                            "left" => {
1295                                let angle = arena.create_token(EnumToken::AngleTokenType, TokenValue::Num(270.0), Some("deg"));
1296                                slice.splice(iu..k + 1, [angle]);
1297                            }
1298                            "top" | "bottom" => 'sw: {
1299                                let mut j = k + 1;
1300                                while j < slice.len() && is_ws_or_comment(arena, at(slice, j)) {
1301                                    j += 1;
1302                                }
1303                                if j < slice.len() && typ_of(arena, at(slice, j)) != EnumToken::CommaTokenType {
1304                                    i = j as isize - 1;
1305                                    break 'sw;
1306                                }
1307                                if key == "bottom" {
1308                                    while k < slice.len() && typ_of(arena, at(slice, k)) != EnumToken::CommaTokenType {
1309                                        k += 1;
1310                                    }
1311                                    let end = (k + 1).min(slice.len());
1312                                    slice.drain(iu..end);
1313                                    i -= 1;
1314                                    break 'sw;
1315                                }
1316                                let angle = arena.create_token(EnumToken::AngleTokenType, TokenValue::Num(if key == "top" { 0.0 } else { 180.0 }), Some("deg"));
1317                                slice.splice(iu..k + 1, [angle]);
1318                                i -= 1;
1319                            }
1320                            _ => {}
1321                        }
1322                    }
1323                } else if ti == EnumToken::AngleTokenType {
1324                    let degrees = arena.numeric_value.get(to_degrees(arena, slice[iu]));
1325                    if (180.0 - degrees) % 360.0 == 0.0 {
1326                        let k = iu + 1;
1327                        let end = (k + 1).min(slice.len());
1328                        slice.drain(iu..end);
1329                    }
1330                }
1331                i += 1;
1332            }
1333            let mut i = i.max(0) as usize;
1334            if typ_of(arena, at(slice, i)) == EnumToken::CommaTokenType {
1335                i += 1;
1336            }
1337            if typ_of(arena, at(slice, i)) == EnumToken::ColorTokenType {
1338                let mut stops: Vec<u32> = slice.drain(i..).collect();
1339                reduce_color_stops(arena, &mut stops);
1340                slice.extend(stops);
1341            }
1342        }
1343        "radial-gradient" | "repeating-radial-gradient" => {
1344            let mut i = 0usize;
1345            let mut positions: Vec<u32> = Vec::new();
1346            let mut form: Vec<u32> = Vec::new();
1347            let mut size: Vec<u32> = Vec::new();
1348            let mut color_space_def: Vec<u32> = Vec::new();
1349            for _ in 0..2 {
1350                if typ_of(arena, at(slice, i)) == EnumToken::IdenTokenType {
1351                    let tk = at(slice, i);
1352                    if str_eq(arena, tk, "farthest-corner") || str_eq(arena, tk, "ellipse") {
1353                        i += 1;
1354                    } else if str_eq(arena, tk, "closest-side") || str_eq(arena, tk, "closest-corner") || str_eq(arena, tk, "farthest-side") {
1355                        size.push(slice[i]);
1356                        i += 1;
1357                    } else if str_eq(arena, tk, "circle") {
1358                        form.push(slice[i]);
1359                        i += 1;
1360                    }
1361                    while is_ws_or_comment(arena, at(slice, i)) {
1362                        i += 1;
1363                    }
1364                }
1365            }
1366            if typ_of(arena, at(slice, i)) == EnumToken::IdenTokenType && str_eq(arena, at(slice, i), "at") {
1367                i += 1;
1368            }
1369            while is_ws_or_comment(arena, at(slice, i)) {
1370                i += 1;
1371            }
1372            let tk = at(slice, i);
1373            let tt = typ_of(arena, tk);
1374            if tt == EnumToken::PercentageTokenType
1375                || (tt == EnumToken::NumberTokenType && arena.numeric_value.get(tk.unwrap()) == 0.0)
1376                || (tt == EnumToken::IdenTokenType && ["center", "top", "bottom", "left", "right"].iter().any(|k| str_eq(arena, tk, k)))
1377            {
1378                loop {
1379                    if typ_of(arena, at(slice, i)) == EnumToken::IdenTokenType && at(slice, i).is_some_and(|x| arena.string_equals(arena.string_value.get(x), "in")) {
1380                        break;
1381                    }
1382                    if let Some(&x) = slice.get(i) {
1383                        positions.push(x);
1384                    }
1385                    i += 1;
1386                    if !(i < slice.len() && typ_of(arena, at(slice, i)) != EnumToken::CommaTokenType) {
1387                        break;
1388                    }
1389                }
1390            }
1391            while i < slice.len() && typ_of(arena, at(slice, i)) != EnumToken::CommaTokenType {
1392                color_space_def.push(slice[i]);
1393                i += 1;
1394            }
1395            if typ_of(arena, at(slice, i)) == EnumToken::CommaTokenType {
1396                i += 1;
1397            }
1398            if !positions.is_empty() {
1399                let mut position1 = String::new();
1400                let mut position2 = String::new();
1401                let mut k = 0usize;
1402                while k < positions.len() {
1403                    let p = positions[k];
1404                    let pt = arena.data_types.get(p);
1405                    if pt == EnumToken::IdenTokenType {
1406                        let v = arena.resolve_string(arena.string_value.get(p)).to_string();
1407                        if position1.is_empty() {
1408                            position1 = v;
1409                        } else {
1410                            position2 = v;
1411                        }
1412                    } else if pt == EnumToken::PercentageTokenType || pt == EnumToken::NumberTokenType {
1413                        let v = format!("{}%", js_number_to_string(arena.numeric_value.get(p)));
1414                        if position1.is_empty() {
1415                            position1 = v;
1416                        } else {
1417                            position2 = v;
1418                        }
1419                    }
1420                    if !position2.is_empty() {
1421                        break;
1422                    }
1423                    k += 1;
1424                }
1425                if !position1.is_empty() {
1426                    let key = format!("{} {}", position1, position2).trim().to_string();
1427                    let pc = |v: f64| arena.create_token(EnumToken::PercentageTokenType, TokenValue::Num(v), None);
1428                    let iden = |v: &str| arena.create_token(EnumToken::IdenTokenType, TokenValue::Str(v), None);
1429                    match key.as_str() {
1430                        "50% 50%" | "center center" | "50%" | "center" => positions.clear(),
1431                        // a single value is centered vertically: both values are kept
1432                        "0% 0%" | "0 0" | "top left" | "left top" => positions = vec![pc(0.0), ws(0), pc(0.0)],
1433                        "50% 0%" | "50% 0" | "center top" | "top center" => positions = vec![iden("top")],
1434                        "top right" | "right top" => positions = vec![pc(100.0), ws(0), pc(0.0)],
1435                        "0 50%" | "0% 50%" | "left center" | "center left" => positions = vec![iden("left")],
1436                        "100% 50%" | "right center" | "center right" => positions = vec![iden("right")],
1437                        "0 100%" | "0% 100%" | "left bottom" | "bottom left" => positions = vec![pc(0.0), ws(0), pc(100.0)],
1438                        "50% 100%" | "center bottom" | "bottom center" => positions = vec![iden("bottom")],
1439                        "100% 100%" | "right bottom" | "bottom right" => positions = vec![pc(100.0), ws(0), pc(100.0)],
1440                        _ => {}
1441                    }
1442                }
1443            }
1444            let mut result: Vec<u32> = Vec::new();
1445            result.extend(form);
1446            if !size.is_empty() {
1447                if !result.is_empty() {
1448                    result.push(ws(0));
1449                }
1450                result.extend(size);
1451            }
1452            if !positions.is_empty() {
1453                if !result.is_empty() {
1454                    result.push(ws(0));
1455                }
1456                result.push(arena.create_token(EnumToken::IdenTokenType, TokenValue::Str("at"), None));
1457                result.push(ws(0));
1458                result.extend(positions);
1459            }
1460            if !color_space_def.is_empty() {
1461                if !result.is_empty() {
1462                    result.push(ws(0));
1463                }
1464                result.extend(color_space_def);
1465            }
1466            if !result.is_empty() {
1467                result.push(arena.create_token(EnumToken::CommaTokenType, TokenValue::None, None));
1468            }
1469            let mut stops: Vec<u32> = slice.get(i..).map_or_else(Vec::new, |s| s.to_vec());
1470            reduce_color_stops(arena, &mut stops);
1471            result.extend(stops);
1472            *slice = result;
1473        }
1474        "conic-gradient" | "repeating-conic-gradient" => {
1475            let mut i = 0usize;
1476            let mut angles: Vec<u32> = Vec::new();
1477            let mut positions: Vec<u32> = Vec::new();
1478            let mut color_space_def: Vec<u32> = Vec::new();
1479            if typ_of(arena, at(slice, i)) == EnumToken::IdenTokenType && str_eq(arena, at(slice, i), "from") {
1480                angles.push(slice[i]);
1481                i += 1;
1482                while i < slice.len() && is_ws_or_comment(arena, at(slice, i)) {
1483                    angles.push(slice[i]);
1484                    i += 1;
1485                }
1486                let tt = typ_of(arena, at(slice, i));
1487                if (tt == EnumToken::NumberTokenType || tt == EnumToken::AngleTokenType) && arena.numeric_value.get(to_degrees(arena, slice[i])) == 0.0 {
1488                    angles.clear();
1489                    i += 1;
1490                } else if tt != EnumToken::CommaTokenType && tt != EnumToken::IdenTokenType {
1491                    if let Some(&x) = slice.get(i) {
1492                        angles.push(x);
1493                    }
1494                    i += 1;
1495                }
1496                while i < slice.len() && is_ws_or_comment(arena, at(slice, i)) {
1497                    i += 1;
1498                }
1499            }
1500            if typ_of(arena, at(slice, i)) == EnumToken::IdenTokenType && str_eq(arena, at(slice, i), "at") {
1501                i += 1;
1502                while i < slice.len() && is_ws_or_comment(arena, at(slice, i)) {
1503                    i += 1;
1504                }
1505                let mut position1 = String::new();
1506                let mut position2 = String::new();
1507                for pos in 0..2 {
1508                    let tk = at(slice, i);
1509                    let tt = typ_of(arena, tk);
1510                    let value = if tt == EnumToken::IdenTokenType && !str_eq(arena, tk, "in") {
1511                        Some(arena.resolve_string(arena.string_value.get(tk.unwrap())).to_string())
1512                    } else if tt == EnumToken::PercentageTokenType || tt == EnumToken::NumberTokenType {
1513                        Some(format!("{}%", js_number_to_string(arena.numeric_value.get(tk.unwrap()))))
1514                    } else {
1515                        None
1516                    };
1517                    if let Some(v) = value {
1518                        if pos == 0 {
1519                            position1 = v;
1520                        } else {
1521                            position2 = v;
1522                        }
1523                        positions.push(slice[i]);
1524                        i += 1;
1525                    }
1526                    while i < slice.len() && is_ws_or_comment(arena, at(slice, i)) {
1527                        if pos == 0 {
1528                            positions.push(slice[i]);
1529                        }
1530                        i += 1;
1531                    }
1532                }
1533                if !position1.is_empty() {
1534                    let key = format!("{} {}", position1, position2).trim().to_string();
1535                    reducegradient_background_position(arena, &mut positions, &key);
1536                }
1537            }
1538            while i < slice.len() && is_ws_or_comment(arena, at(slice, i)) {
1539                i += 1;
1540            }
1541            if typ_of(arena, at(slice, i)) == EnumToken::IdenTokenType && str_eq(arena, at(slice, i), "in") {
1542                while i < slice.len() && typ_of(arena, at(slice, i)) != EnumToken::CommaTokenType {
1543                    color_space_def.push(slice[i]);
1544                    i += 1;
1545                }
1546            }
1547            if typ_of(arena, at(slice, i)) == EnumToken::CommaTokenType {
1548                i += 1;
1549            }
1550            let mut result: Vec<u32> = Vec::new();
1551            if !positions.is_empty() {
1552                if !angles.is_empty() {
1553                    angles.push(ws(0));
1554                }
1555                angles.push(arena.create_token(EnumToken::IdenTokenType, TokenValue::Str("at"), None));
1556                angles.push(ws(0));
1557                angles.extend(positions);
1558            }
1559            if !angles.is_empty() {
1560                result.extend(angles);
1561                result.push(arena.create_token(EnumToken::CommaTokenType, TokenValue::None, None));
1562            }
1563            if !color_space_def.is_empty() {
1564                if !result.is_empty() {
1565                    result.push(ws(0));
1566                }
1567                result.extend(color_space_def);
1568                result.push(arena.create_token(EnumToken::CommaTokenType, TokenValue::None, None));
1569            }
1570            let mut stops: Vec<u32> = slice.get(i..).map_or_else(Vec::new, |s| s.to_vec());
1571            reduce_conic_color_stops(arena, &mut stops);
1572            result.extend(stops);
1573            *slice = result;
1574        }
1575        _ => {}
1576    }
1577}
1578
1579/// render a token (`renderToken()`)
1580fn render_token(arena: &AstArena, token: u32, options: &RenderOptions, cache: Option<&RenderCache>, reducer: Option<&Reducer>) -> String {
1581    let t = |x: u32| arena.data_types.get(x);
1582    let typ = t(token);
1583    let supports_options;
1584    let (options, reducer) = if typ == EnumToken::WhenElseFunctionTokenType && arena.string_equals_ignore_case(arena.string_value.get(token), "supports") {
1585        supports_options = RenderOptions { minify_values: Some(false), minify: Some(false), convert_color: Some(ConvertColor::Bool(false)), ..options.clone() };
1586        (&supports_options, None)
1587    } else {
1588        (options, reducer)
1589    };
1590    // `options.minifyValues ??= options.minify`
1591    let minify_values = options.minify_values.or(options.minify) == Some(true);
1592    let effective;
1593    let options = if options.minify_values.is_none() && options.minify.is_some() {
1594        effective = RenderOptions { minify_values: options.minify, ..options.clone() };
1595        &effective
1596    } else {
1597        options
1598    };
1599    let s = |id: u32| arena.resolve_string(id);
1600    let own_reducer;
1601    match typ {
1602        EnumToken::UrlFunctionTokenDefType
1603        | EnumToken::FunctionTokenDefType
1604        | EnumToken::MathFunctionTokenDefType
1605        | EnumToken::ImageFunctionTokenDefType
1606        | EnumToken::ColorFunctionTokenDefType
1607        | EnumToken::TimingFunctionTokenDefType
1608        | EnumToken::WhenElseFunctionTokenDefType
1609        | EnumToken::SupportsFunctionTokenDefType
1610        | EnumToken::TimelineFunctionTokenDefType
1611        | EnumToken::GridTemplateFuncTokenDefType
1612        | EnumToken::TransformFunctionTokenDefType
1613        | EnumToken::ContainerFunctionTokenDefType
1614        | EnumToken::PseudoClassFunctionTokenDefType
1615        | EnumToken::GeneralEnclosedFunctionTokenDefType
1616        | EnumToken::CustomFunctionTokenDefType
1617        | EnumToken::WildCardFunctionTokenDefType => format!("{}(", s(arena.string_value.get(token))),
1618        EnumToken::ListToken => render_list(arena, arena.first_token.get(token), options, cache, None),
1619        EnumToken::BinaryExpressionTokenType => {
1620            let op = arena.numeric_value.get(token) as u8;
1621            let l = arena.get_child_at(token, TokenField::L).map_or(0, |_| arena.field(token, TokenField::L));
1622            let r = arena.get_child_at(token, TokenField::R).map_or(0, |_| arena.field(token, TokenField::R));
1623            let needs_parens = |x: u32| t(x) == EnumToken::BinaryExpressionTokenType && matches!(arena.numeric_value.get(x) as u8, EnumToken::Add | EnumToken::Sub);
1624            if op == EnumToken::Mul || op == EnumToken::Div {
1625                let mut result = if needs_parens(l) {
1626                    format!("({})", render_value_with(arena, l, options, cache, None))
1627                } else {
1628                    render_value_with(arena, l, options, cache, None).into()
1629                };
1630                result.push(if op == EnumToken::Mul { '*' } else { '/' });
1631                if needs_parens(r) {
1632                    result.push_str(&format!("({})", render_value_with(arena, r, options, cache, None)));
1633                } else {
1634                    result.push_str(&render_value_with(arena, r, options, cache, None));
1635                }
1636                return result;
1637            }
1638            format!("{}{}{}", render_value_with(arena, l, options, cache, None), if op == EnumToken::Add { " + " } else { " - " }, render_value_with(arena, r, options, cache, None))
1639        }
1640        EnumToken::FractionTokenType => {
1641            let numerator = arena.first_child.get(token);
1642            let denominator = arena.last_child.get(token);
1643            let fraction = format!("{}/{}", render_value_default(arena, numerator), render_value_default(arena, denominator));
1644            if arena.numeric_value.get(denominator) != 0.0 {
1645                let value = minify_number(arena.numeric_value.get(numerator) / arena.numeric_value.get(denominator));
1646                if value.len() <= fraction.len() {
1647                    return value;
1648                }
1649            }
1650            fraction
1651        }
1652        EnumToken::Add => " + ".into(),
1653        EnumToken::Sub => " - ".into(),
1654        EnumToken::UniversalSelectorTokenType | EnumToken::Star | EnumToken::Mul => "*".into(),
1655        EnumToken::Div => "/".into(),
1656        EnumToken::WrappedValuesTokenType => format!("{{{}}}", render_list(arena, arena.first_token.get(token), options, cache, None)),
1657        EnumToken::ColorTokenType => {
1658            if arena.color_type.get(token) == ColorType::LIGHT_DARK
1659                || (arena.first_token.get(token) != 0 && options.convert_color == Some(ConvertColor::Bool(false)) && arena.token_count(token) == 2)
1660            {
1661                let mut result = String::new();
1662                for curr in arena.token_iter(token) {
1663                    if t(curr) == EnumToken::IdenTokenType {
1664                        parse_color(arena, curr);
1665                    }
1666                    result.push_str(&render_value_with(arena, curr, options, cache, None));
1667                }
1668                return format!("{}({})", s(arena.string_value.get(token)), result);
1669            }
1670            render_color(arena, token, options, cache, reducer)
1671        }
1672        EnumToken::UrlFunctionTokenType
1673        | EnumToken::ParensTokenType
1674        | EnumToken::FunctionTokenType
1675        | EnumToken::MathFunctionTokenType
1676        | EnumToken::ImageFunctionTokenType
1677        | EnumToken::TimingFunctionTokenType
1678        | EnumToken::PseudoClassFuncTokenType
1679        | EnumToken::WhenElseFunctionTokenType
1680        | EnumToken::TimelineFunctionTokenType
1681        | EnumToken::GridTemplateFuncTokenType
1682        | EnumToken::SupportsFunctionTokenType
1683        | EnumToken::ContainerFunctionTokenType
1684        | EnumToken::TransformFunctionTokenType
1685        | EnumToken::GeneralEnclosedFunctionTokenType
1686        | EnumToken::CustomFunctionTokenType
1687        | EnumToken::WildCardFunctionTokenType => {
1688            if typ == EnumToken::UrlFunctionTokenType && minify_values {
1689                if t(arena.first_token.get(token)) == EnumToken::BadUrlTokenType {
1690                    return "url()".into();
1691                }
1692                for child in arena.token_iter(token) {
1693                    if t(child) == EnumToken::StringTokenType {
1694                        let val = s(arena.string_value.get(child));
1695                        let inner: String = val.chars().skip(1).take(4).collect();
1696                        if inner != "data:" && url_token_matcher(&val) {
1697                            arena.data_types.set(child, EnumToken::UrlTokenTokenType);
1698                            let unquoted: String = {
1699                                let c: Vec<char> = val.chars().collect();
1700                                c[1..c.len() - 1].iter().collect()
1701                            };
1702                            arena.string_value.set(child, arena.intern_string(&unquoted));
1703                        }
1704                        break;
1705                    }
1706                }
1707            }
1708            if typ == EnumToken::ImageFunctionTokenType && minify_values {
1709                let mut slice = arena.tokens(token);
1710                minify_gradient(arena, token, &mut slice);
1711                let reducer_ref: &Reducer = match reducer {
1712                    Some(r) => r,
1713                    None => {
1714                        own_reducer = Reducer::new(options, cache);
1715                        &own_reducer
1716                    }
1717                };
1718                let mut result = String::new();
1719                for &tk in &slice {
1720                    reducer_ref.reduce(arena, &mut result, tk);
1721                }
1722                return format!("{}({})", s(arena.string_value.get(token)), result);
1723            }
1724            if typ == EnumToken::MathFunctionTokenType && arena.token_count(token) == 1 {
1725                let first = arena.first_token.get(token);
1726                let first_type = t(first);
1727                if first_type != EnumToken::BinaryExpressionTokenType
1728                    && first_type != EnumToken::FractionTokenType
1729                    && first_type != EnumToken::IdenTokenType
1730                    && !arena.has_fraction(first)
1731                {
1732                    let reducer_ref: &Reducer = match reducer {
1733                        Some(r) => r,
1734                        None => {
1735                            own_reducer = Reducer::new(options, cache);
1736                            &own_reducer
1737                        }
1738                    };
1739                    return format!("{}({})", s(arena.string_value.get(token)), render_value_with(arena, first, options, cache, Some(reducer_ref)));
1740                }
1741            }
1742            format!("{}({})", s(arena.string_value.get(token)), render_reduced(arena, arena.first_token.get(token), options, cache, reducer))
1743        }
1744        EnumToken::BlockStartTokenType => "{".into(),
1745        EnumToken::BlockEndTokenType => "}".into(),
1746        EnumToken::StartParensTokenType => "(".into(),
1747        EnumToken::DelimTokenType | EnumToken::EqualMatchTokenType => "=".into(),
1748        EnumToken::IncludeMatchTokenType => "~=".into(),
1749        EnumToken::DashMatchTokenType => "|=".into(),
1750        EnumToken::StartMatchTokenType => "^=".into(),
1751        EnumToken::EndMatchTokenType => "$=".into(),
1752        EnumToken::ContainMatchTokenType => "*=".into(),
1753        EnumToken::LtTokenType => "<".into(),
1754        EnumToken::LteTokenType => "<=".into(),
1755        EnumToken::Tilda | EnumToken::SubsequentSiblingCombinatorTokenType => "~".into(),
1756        EnumToken::Plus | EnumToken::NextSiblingCombinatorTokenType => "+".into(),
1757        EnumToken::GtTokenType | EnumToken::ChildCombinatorTokenType => ">".into(),
1758        EnumToken::GteTokenType => ">=".into(),
1759        EnumToken::ColumnCombinatorTokenType => "||".into(),
1760        EnumToken::EndParensTokenType => ")".into(),
1761        EnumToken::AttrStartTokenType => "[".into(),
1762        EnumToken::AttrEndTokenType => "]".into(),
1763        EnumToken::DescendantCombinatorTokenType | EnumToken::WhitespaceTokenType => " ".into(),
1764        EnumToken::ColonTokenType => ":".into(),
1765        EnumToken::DoubleColonTokenType => "::".into(),
1766        EnumToken::SemiColonTokenType => ";".into(),
1767        EnumToken::CommaTokenType => ",".into(),
1768        EnumToken::ImportantTokenType => "!important".into(),
1769        EnumToken::PipeTokenType => "|".into(),
1770        EnumToken::AttrTokenType | EnumToken::IdenListTokenType => format!("[{}]", render_reduced(arena, arena.first_token.get(token), options, cache, reducer)),
1771        EnumToken::TimeTokenType
1772        | EnumToken::AngleTokenType
1773        | EnumToken::LengthTokenType
1774        | EnumToken::DimensionTokenType
1775        | EnumToken::FrequencyTokenType
1776        | EnumToken::ResolutionTokenType
1777        | EnumToken::UserDefinedDimensionTokenType => render_dimension(arena, token, options, cache, minify_values),
1778        EnumToken::FlexTokenType | EnumToken::PercentageTokenType => {
1779            let uni = if typ == EnumToken::PercentageTokenType { "%" } else { "fr" };
1780            let perc = if arena.has_fraction(token) {
1781                String::from(render_value_with(arena, arena.get_fraction(token), options, cache, None))
1782            } else {
1783                minify_number(arena.numeric_value.get(token))
1784            };
1785            if minify_values && perc == "0" {
1786                "0".into()
1787            } else if perc.contains('/') {
1788                perc.replacen('/', &format!("{}/", uni), 1)
1789            } else {
1790                format!("{}{}", perc, uni)
1791            }
1792        }
1793        EnumToken::NumberTokenType => {
1794            if arena.has_fraction(token) {
1795                String::from(render_value_with(arena, arena.get_fraction(token), options, cache, None))
1796            } else {
1797                minify_number(arena.numeric_value.get(token))
1798            }
1799        }
1800        EnumToken::InfinityTokenType => "1/0".into(),
1801        EnumToken::NegativeInfinityTokenType => "-1/0".into(),
1802        EnumToken::NaNTokenType => "NaN".into(),
1803        EnumToken::AtRuleTokenType => format!("@{}", s(arena.name.get(token))),
1804        EnumToken::CommentTokenType | EnumToken::CDOCOMMNodeType => {
1805            if options.remove_comments == Some(true)
1806                && (options.preserve_license != Some(true) || !arena.string_starts_with(arena.string_value.get(token), "/*!"))
1807            {
1808                return String::new();
1809            }
1810            s(arena.string_value.get(token)).to_string()
1811        }
1812        EnumToken::PseudoClassTokenType | EnumToken::PseudoElementTokenType => {
1813            let v = s(arena.string_value.get(token));
1814            if typ == EnumToken::PseudoElementTokenType {
1815                let rest: String = v.chars().skip(1).collect();
1816                if PSEUDO_ELEMENTS.contains(&rest.as_str()) {
1817                    return rest;
1818                }
1819            }
1820            v.to_string()
1821        }
1822        EnumToken::CssTypeTokenType
1823        | EnumToken::UrlTokenTokenType
1824        | EnumToken::HashTokenType
1825        | EnumToken::IdenTokenType
1826        | EnumToken::StringTokenType
1827        | EnumToken::LiteralTokenType
1828        | EnumToken::UniCodeRange
1829        | EnumToken::DashedIdenTokenType
1830        | EnumToken::PseudoPageTokenType
1831        | EnumToken::ClassSelectorTokenType => s(arena.string_value.get(token)).to_string(),
1832        EnumToken::NestingSelectorTokenType => "&".into(),
1833        EnumToken::SupportsQueryUnaryConditionTokenType | EnumToken::WhenElseUnaryConditionTokenType | EnumToken::MediaQueryUnaryFeatureTokenType => {
1834            format!(
1835                "{} {}",
1836                render_value_with(arena, arena.field(token, TokenField::L), options, cache, reducer),
1837                render_field(arena, token, TokenField::R, options, cache, reducer)
1838            )
1839        }
1840        EnumToken::SupportsQueryConditionTokenType | EnumToken::WhenElseQueryConditionTokenType => format!(
1841            "{} {} {}",
1842            render_field(arena, token, TokenField::L, options, cache, reducer),
1843            render_value_with(arena, arena.field(token, TokenField::Op), options, cache, reducer),
1844            render_field(arena, token, TokenField::R, options, cache, reducer)
1845        ),
1846        EnumToken::IfConditionTokenType => {
1847            if !arena.has_field(token, TokenField::L) {
1848                return String::new();
1849            }
1850            format!(
1851                "{}:{}{}",
1852                render_field(arena, token, TokenField::L, options, cache, reducer),
1853                options.indent.as_deref().unwrap_or(""),
1854                render_field(arena, token, TokenField::R, options, cache, reducer)
1855            )
1856        }
1857        EnumToken::IfElseConditionTokenType => format!(
1858            "{}{}{}",
1859            render_value_with(arena, arena.field(token, TokenField::L), options, cache, reducer),
1860            options.indent.as_deref().unwrap_or(""),
1861            render_value_with(arena, arena.field(token, TokenField::R), options, cache, reducer)
1862        ),
1863        EnumToken::DeclarationNodeType => {
1864            let mut values = arena.tokens(token);
1865            if minify_values {
1866                filter_values(arena, &mut values);
1867            }
1868            let mut result = format!("{}:", s(arena.name.get(token)));
1869            for v in values {
1870                result.push_str(&render_value_with(arena, v, options, cache, reducer));
1871            }
1872            result
1873        }
1874        EnumToken::MediaQueryConditionTokenType => {
1875            let op = arena.field(token, TokenField::Op);
1876            let indent = if matches!(
1877                t(op),
1878                EnumToken::LtTokenType | EnumToken::GtTokenType | EnumToken::ColonTokenType | EnumToken::DelimTokenType | EnumToken::LteTokenType | EnumToken::GteTokenType
1879            ) {
1880                ""
1881            } else {
1882                " "
1883            };
1884            format!(
1885                "{}{}{}{}{}",
1886                render_field(arena, token, TokenField::L, options, cache, reducer),
1887                indent,
1888                render_value_with(arena, op, options, cache, reducer),
1889                indent,
1890                render_field(arena, token, TokenField::R, options, cache, reducer)
1891            )
1892        }
1893        EnumToken::MediaRangeQueryTokenType => format!(
1894            "{}{}{}{}{}",
1895            render_field(arena, token, TokenField::L, options, cache, reducer),
1896            render_value_with(arena, arena.field(token, TokenField::Op), options, cache, reducer),
1897            render_field(arena, token, TokenField::Val, options, cache, reducer),
1898            render_value_with(arena, arena.field(token, TokenField::Op2), options, cache, reducer),
1899            render_field(arena, token, TokenField::R, options, cache, reducer)
1900        ),
1901        EnumToken::MediaFeatureTokenType => s(arena.string_value.get(token)).to_string(),
1902        EnumToken::NotTokenType => "not".into(),
1903        EnumToken::OnlyTokenType => "only".into(),
1904        EnumToken::AndTokenType => "and".into(),
1905        EnumToken::OrTokenType => "or".into(),
1906        EnumToken::BadCommentTokenType | EnumToken::BadCdoTokenType | EnumToken::BadStringTokenType | EnumToken::BadUrlTokenType | EnumToken::EOFTokenType => {
1907            String::new()
1908        }
1909        EnumToken::ComposesSelectorNodeType => format!(
1910            "{}{}",
1911            render_field(arena, token, TokenField::L, options, cache, reducer),
1912            if !arena.has_field(token, TokenField::R) {
1913                String::new()
1914            } else {
1915                format!(" from {}", render_value_with(arena, arena.field(token, TokenField::R), options, cache, reducer))
1916            }
1917        ),
1918        // typescript throws `Unsupported token type`
1919        _ => String::new(),
1920    }
1921}
1922
1923/// render a dimension: the angles are rendered in the shortest unit, the zero dimensions without unit
1924fn render_dimension(arena: &AstArena, token: u32, options: &RenderOptions, cache: Option<&RenderCache>, minify_values: bool) -> String {
1925    let typ = arena.data_types.get(token);
1926    let mut val = if arena.has_fraction(token) {
1927        String::from(render_value_with(arena, arena.get_fraction(token), options, cache, None))
1928    } else {
1929        minify_number(arena.numeric_value.get(token))
1930    };
1931    let mut unit = arena.resolve_string(arena.unit.get(token)).to_string();
1932    if typ == EnumToken::AngleTokenType && !val.contains('/') {
1933        let angle = get_angle(arena, token);
1934        let mut value = format!("{}{}", val, unit);
1935        let original_unit = unit.clone();
1936        for u in ["deg", "turn", "rad", "grad"] {
1937            if original_unit == u {
1938                continue;
1939            }
1940            let (factor, extra) = match u {
1941                "deg" => (360.0, 3),
1942                "turn" => (1.0, 4),
1943                "rad" => (2.0 * std::f64::consts::PI, 3),
1944                _ => (400.0, 4),
1945            };
1946            let v = minify_str(&to_fixed(to_precision_angle(angle * factor, anglePrecision, false), anglePrecision as usize));
1947            if v.len() + extra < value.len() {
1948                val = v.clone();
1949                unit = u.to_string();
1950                value = format!("{}{}", v, u);
1951            }
1952        }
1953    }
1954    if val == "0" {
1955        return match typ {
1956            EnumToken::TimeTokenType => "0s".into(),
1957            EnumToken::FrequencyTokenType => "0Hz".into(),
1958            EnumToken::ResolutionTokenType => "0x".into(),
1959            _ => {
1960                if minify_values {
1961                    "0".into()
1962                } else {
1963                    format!("0{}", unit)
1964                }
1965            }
1966        };
1967    }
1968    if typ == EnumToken::TimeTokenType {
1969        if unit == "ms" {
1970            let v = minify_number(js_parse_number(&val) / 1000.0);
1971            if v.len() < val.len() {
1972                return format!("{}s", v);
1973            }
1974            return format!("{}ms", val);
1975        }
1976        return format!("{}s", val);
1977    }
1978    if typ == EnumToken::ResolutionTokenType && unit == "dppx" {
1979        unit = "x".into();
1980    }
1981    if val.contains('/') {
1982        val.replacen('/', &format!("{}/", unit), 1)
1983    } else {
1984        format!("{}{}", minify_number(to_precision_value(js_parse_number(&val), crate::syntax::constants::colorPrecision)), unit)
1985    }
1986}
1987
1988/// remove the whitespace that is not needed: before `!important`, after a function
1989pub fn filter_values(arena: &AstArena, values: &mut Vec<u32>) {
1990    let t = |x: u32| arena.data_types.get(x);
1991    let mut i = 0usize;
1992    while i < values.len() {
1993        if t(values[i]) == EnumToken::ImportantTokenType && i > 0 && t(values[i - 1]) == EnumToken::WhitespaceTokenType {
1994            values.remove(i - 1);
1995        } else if is_function_type(t(values[i]))
1996            && (t(values[i]) != EnumToken::ColorTokenType || arena.first_token.get(values[i]) != 0)
1997            && t(values[i]) != EnumToken::WildCardFunctionTokenType
1998            && values.get(i + 1).is_some_and(|&n| t(n) == EnumToken::WhitespaceTokenType)
1999        {
2000            values.remove(i + 1);
2001        }
2002        i += 1;
2003    }
2004}