Skip to main content

rust_css_parser/parser/declaration/
mod.rs

1//! Port of `src/parser/declaration/*`: shorthand computation and duplicate declaration removal.
2//!
3//! The typescript `Map`s are insertion ordered: [`JsMap`] (a key set again keeps its position, a deleted key set again
4//! moves to the end). The shorthand configuration (`properties.json`) is read as json values, like the typescript
5//! property accesses.
6
7pub mod list;
8pub mod map;
9pub mod set;
10
11use crate::ast::arena::{AstArena, TokenValue};
12use crate::ast::types::EnumToken;
13use serde_json::Value;
14
15/// insertion ordered map with the semantics of the javascript `Map`
16#[derive(Clone, Debug)]
17pub struct JsMap<V> {
18    /// the keys are shared strings: an interned name of the arena is stored without a copy
19    entries: Vec<(SharedStr, V)>,
20}
21
22impl<V> Default for JsMap<V> {
23    fn default() -> Self {
24        Self { entries: Vec::new() }
25    }
26}
27
28impl<V> JsMap<V> {
29    pub fn new() -> Self {
30        Self::default()
31    }
32
33    fn index(&self, key: &str) -> Option<usize> {
34        self.entries.iter().position(|(k, _)| &**k == key)
35    }
36
37    pub fn has(&self, key: &str) -> bool {
38        self.index(key).is_some()
39    }
40
41    pub fn get(&self, key: &str) -> Option<&V> {
42        self.index(key).map(|i| &self.entries[i].1)
43    }
44
45    pub fn get_mut(&mut self, key: &str) -> Option<&mut V> {
46        self.index(key).map(move |i| &mut self.entries[i].1)
47    }
48
49    /// set a value: an existing key keeps its position
50    pub fn set(&mut self, key: impl AsRef<str> + Into<SharedStr>, value: V) {
51        match self.index(key.as_ref()) {
52            Some(i) => self.entries[i].1 = value,
53            None => self.entries.push((key.into(), value)),
54        }
55    }
56
57    pub fn delete(&mut self, key: &str) -> bool {
58        match self.index(key) {
59            Some(i) => {
60                self.entries.remove(i);
61                true
62            }
63            None => false,
64        }
65    }
66
67    pub fn clear(&mut self) {
68        self.entries.clear();
69    }
70
71    pub fn len(&self) -> usize {
72        self.entries.len()
73    }
74
75    pub fn is_empty(&self) -> bool {
76        self.entries.is_empty()
77    }
78
79    pub fn keys(&self) -> impl Iterator<Item = &str> {
80        self.entries.iter().map(|(k, _)| &**k)
81    }
82
83    pub fn values(&self) -> impl Iterator<Item = &V> {
84        self.entries.iter().map(|(_, v)| v)
85    }
86
87    pub fn iter(&self) -> impl Iterator<Item = (&str, &V)> {
88        self.entries.iter().map(|(k, v)| (&**k, v))
89    }
90}
91
92/// `key in object`
93pub(crate) fn has_key(v: &Value, key: &str) -> bool {
94    v.as_object().is_some_and(|o| o.contains_key(key))
95}
96
97/// a string array of the configuration (empty when missing)
98pub(crate) fn str_list(v: &Value) -> Vec<&str> {
99    v.as_array().map(|a| a.iter().filter_map(|s| s.as_str()).collect()).unwrap_or_default()
100}
101
102/// `EnumToken[config.typ]`
103pub(crate) fn config_type(config: &Value) -> u8 {
104    config.get("typ").and_then(|t| t.as_str()).and_then(EnumToken::value).unwrap_or(0)
105}
106
107/// create a token from the shorthand configuration (a whitespace without configuration)
108pub(crate) fn config_token(arena: &AstArena, config: Option<&Value>) -> u32 {
109    match config.filter(|c| !c.is_null()) {
110        None => arena.create_token(EnumToken::WhitespaceTokenType, TokenValue::None, None),
111        Some(config) => {
112            let val = config.get("val").and_then(|v| v.as_str());
113            arena.create_token(config_type(config), val.map_or(TokenValue::None, TokenValue::Str), None)
114        }
115    }
116}
117
118/// true if the token matches the configuration token
119pub(crate) fn match_config_token(arena: &AstArena, token: u32, config: Option<&Value>) -> bool {
120    let Some(config) = config.filter(|c| !c.is_null()) else {
121        return false;
122    };
123    arena.data_types.get(token) == config_type(config)
124        && config.get("val").and_then(|v| v.as_str()).is_none_or(|val| arena.string_equals(arena.string_value.get(token), val))
125}
126
127use std::cell::RefCell;
128use std::rc::Rc;
129use crate::ast::strings::SharedStr;
130
131/// a value of the declaration maps: a declaration node, or a set / map of declarations shared by reference
132#[derive(Clone)]
133pub enum DeclEntry {
134    Node(u32),
135    Set(Rc<RefCell<set::PropertySet>>),
136    Map(Rc<RefCell<map::PropertyMap>>),
137}
138
139/// the declarations of entries: the sets and the maps are iterated (`[Symbol.iterator]()`, which may compute a
140/// shorthand: each iteration runs it again, like the typescript iterators)
141pub fn flatten<'a>(arena: &AstArena, entries: impl IntoIterator<Item = &'a DeclEntry>) -> Vec<u32> {
142    let entries = entries.into_iter();
143    let mut result = Vec::with_capacity(entries.size_hint().0);
144    for entry in entries {
145        match entry {
146            DeclEntry::Node(n) => result.push(*n),
147            DeclEntry::Set(s) => result.extend(s.borrow_mut().iterate(arena)),
148            DeclEntry::Map(m) => result.extend(m.borrow_mut().iterate(arena)),
149        }
150    }
151    result
152}