Skip to main content

rust_css_parser/ast/features/
shorthand.rs

1//! Port of `src/ast/features/shorthand.ts`.
2
3use super::r#type::FeatureWalkMode;
4use super::{FeatureResult, MinifyFeature, SharedFeature};
5use crate::ast::arena::AstArena;
6use crate::ast::minify::MinifyContext;
7use crate::ast::mixins::utils::move_result;
8use crate::ast::types::{EnumAstNodeStatus, EnumToken};
9use crate::options::ParserOptions;
10use crate::parser::declaration::list::{DeclarationMemo, PropertyList};
11use crate::validation::config::get_syntax_rule;
12use crate::validation::parser::typedef::ValidationSyntaxGroupEnum;
13use std::cell::RefCell;
14use std::rc::Rc;
15
16pub struct ComputeShorthandFeature;
17
18const ACCEPT: [u8; 3] = [EnumToken::RuleNodeType, EnumToken::AtRuleNodeType, EnumToken::KeyframesRuleNodeType];
19
20impl ComputeShorthandFeature {
21    pub fn register(options: &ParserOptions, features: &mut Vec<SharedFeature>) {
22        if options.compute_shorthand == Some(true) {
23            features.push(Rc::new(RefCell::new(ComputeShorthandFeature)));
24        }
25    }
26}
27
28impl MinifyFeature for ComputeShorthandFeature {
29    fn accept(&self) -> Option<&[u8]> {
30        Some(&ACCEPT)
31    }
32
33    fn ordering(&self) -> i32 {
34        5
35    }
36
37    fn process_mode(&self) -> u32 {
38        FeatureWalkMode::Post
39    }
40
41    fn run(&mut self, arena: &AstArena, ast: u32, options: &ParserOptions, _parent: u32, context: &mut MinifyContext, _mode: u32) -> FeatureResult {
42        if arena.flags.get(ast) & EnumAstNodeStatus::HasChildren == 0 || arena.first_child.get(ast) == 0 {
43            return FeatureResult::None;
44        }
45        let t = |x: u32| arena.data_types.get(x);
46        // the keys of the declarations are shared by the rules of the minification
47        let memo: Rc<RefCell<DeclarationMemo>> = context.get_or_insert_with("declarations", || Rc::new(RefCell::new(DeclarationMemo::default()))).clone();
48        let mut do_not_sort = false;
49        let mut descriptors = None;
50        let mut is_function = false;
51        if t(ast) == EnumToken::AtRuleNodeType {
52            match &*arena.resolve_string(arena.name.get(ast)) {
53                "function" => {
54                    do_not_sort = true;
55                    is_function = true;
56                    descriptors = get_syntax_rule(ValidationSyntaxGroupEnum::AtRules, "@function").and_then(|r| r.get_property_descriptors());
57                }
58                "mixin" => do_not_sort = true,
59                _ => {}
60            }
61        }
62        // the children are processed by segments: an at-rule without a block or an `@apply` rule inserts declarations
63        // at its position, the declarations are not moved across it
64        let mut child = arena.first_child.get(ast);
65        while child != 0 {
66            let mut list = PropertyList::new(options, Some(memo.clone()), descriptors.clone());
67            let mut has_declarations = false;
68            // first node of the segment that is not moved into the property list
69            let mut first = 0u32;
70            // at-rule without a block that ends the segment
71            let mut boundary = 0u32;
72            while child != 0 {
73                let mut last = child;
74                if !do_not_sort {
75                    // capture comments with the next node
76                    while arena.next_sibling.get(last) != 0 && t(last) == EnumToken::CommentNodeType {
77                        last = arena.next_sibling.get(last);
78                    }
79                }
80                let next = arena.next_sibling.get(last);
81                if t(last) == EnumToken::AtRuleNodeType
82                    && (arena.flags.get(last) & EnumAstNodeStatus::HasChildren == 0 || arena.string_equals(arena.name.get(last), "apply"))
83                {
84                    boundary = child;
85                    child = next;
86                    break;
87                }
88                if do_not_sort || t(last) == EnumToken::DeclarationNodeType {
89                    has_declarations = true;
90                    let mut node = child;
91                    while node != next {
92                        let next_node = arena.next_sibling.get(node);
93                        arena.detach(node);
94                        list.add_declaration(arena, node);
95                        node = next_node;
96                    }
97                } else if first == 0 {
98                    first = child;
99                }
100                child = next;
101            }
102            if has_declarations {
103                // the declarations are inserted before the rules of the segment
104                let reference = if first != 0 { first } else { boundary };
105                for node in list.iterate(arena) {
106                    if reference == 0 {
107                        arena.append_child(ast, node);
108                    } else {
109                        arena.insert_before(reference, &[node]);
110                    }
111                }
112            }
113        }
114        // the deduplicated result keeps the position of the first result: it is moved after the conditional rules
115        if is_function {
116            move_result(arena, ast);
117        }
118        FeatureResult::Node(ast)
119    }
120}