Skip to main content

rust_css_parser/validation/
config.rs

1//! Port of `src/validation/config.ts`.
2
3use super::json::config_json;
4use super::parser::parse::{parse_syntax, trim_syntax_array};
5use super::parser::typedef::{ValidationSyntaxGroupEnum, ValidationTokenEnum as V};
6use super::parser::types::ValidationToken;
7use std::cell::RefCell;
8use crate::utils::fx::HashMap;
9use std::rc::Rc;
10
11/// parsed syntax rule of an at-rule (or a group)
12#[derive(Clone, Debug)]
13pub struct ValidationSyntaxRule {
14    pub optional_body: bool,
15    pub accept_any_declaration: bool,
16    pub accept_any_rule: bool,
17    pub prelude: Rc<Vec<Rc<ValidationToken>>>,
18    pub block: Option<Rc<Vec<Rc<ValidationToken>>>>,
19    pub property_descriptors: Option<Rc<HashMap<String, Rc<Vec<Rc<ValidationToken>>>>>>,
20}
21
22impl ValidationSyntaxRule {
23    pub fn get_prelude_rules(&self) -> Option<Rc<Vec<Rc<ValidationToken>>>> {
24        Some(self.prelude.clone())
25    }
26
27    pub fn get_block_rules(&self) -> Option<Rc<Vec<Rc<ValidationToken>>>> {
28        self.block.clone().filter(|b| !b.is_empty())
29    }
30
31    pub fn get_property_descriptors(&self) -> Option<Rc<HashMap<String, Rc<Vec<Rc<ValidationToken>>>>>> {
32        self.property_descriptors.clone()
33    }
34}
35
36/// the validation configuration
37pub fn get_syntax_config() -> &'static serde_json::Value {
38    config_json()
39}
40
41/// find a syntax definition in a group. aliases use the syntax of the standard property. a `syntaxes` lookup falls
42/// back to the `types` group
43fn lookup_node(group: ValidationSyntaxGroupEnum, key: &str) -> Option<&'static serde_json::Value> {
44    let config = config_json();
45    let entries = &config[group.as_str()];
46    if let Some(node) = entries.get(key) {
47        let mut node = node;
48        let mut i = 0;
49        while let Some(alias) = node.get("alias").and_then(|a| a.as_str()) {
50            if i >= 4 {
51                break;
52            }
53            node = entries.get(alias)?;
54            i += 1;
55        }
56        return if node.get("alias").is_some_and(|a| !a.is_null()) { None } else { Some(node) };
57    }
58    if group == ValidationSyntaxGroupEnum::Syntaxes {
59        return config["types"].get(key);
60    }
61    None
62}
63
64/// number of the syntax groups (`ValidationSyntaxGroupEnum`)
65const GROUPS: usize = 9;
66
67thread_local! {
68    static DEFINED_SYNTAXES: RefCell<HashMap<String, bool>> = RefCell::new(HashMap::default());
69    /// parsed syntaxes, by syntax node: the names that share a definition share the parsed syntax
70    static PARSED_SYNTAXES: RefCell<HashMap<usize, Rc<Vec<Rc<ValidationToken>>>>> = RefCell::new(HashMap::default());
71    /// parsed syntaxes by group (`group as usize`) and name: the lookups borrow the name, it is copied once
72    static PARSED_BY_KEY: RefCell<Vec<HashMap<Box<str>, Option<Rc<Vec<Rc<ValidationToken>>>>>>> =
73        RefCell::new((0..GROUPS).map(|_| HashMap::default()).collect());
74    static SYNTAX_RULES: RefCell<Vec<HashMap<Box<str>, Option<Rc<ValidationSyntaxRule>>>>> =
75        RefCell::new((0..GROUPS).map(|_| HashMap::default()).collect());
76}
77
78thread_local! {
79    /// the definition node of a parsed syntax (by the address of its tokens), see [`syntax_key`]
80    static SYNTAX_NODES: RefCell<HashMap<usize, usize>> = RefCell::new(HashMap::default());
81    /// the key of the definitions that are compiled (`group/name`), by definition node, see [`syntax_key`]
82    static NODE_KEYS: HashMap<usize, String> = {
83        let config = config_json();
84        let mut keys = HashMap::default();
85        for group in ["declarations", "syntaxes", "types"] {
86            if let Some(entries) = config[group].as_object() {
87                for (key, value) in entries {
88                    keys.insert(value as *const serde_json::Value as usize, format!("{}/{}", group, key));
89                }
90            }
91        }
92        keys
93    };
94}
95
96/// the key of the definition of a parsed syntax (`declarations/width`, `types/color`), see `scripts/compile_syntax.rs`.
97/// None if the syntax is not the syntax of a declaration, a type or a function (a descriptor, ...)
98pub fn syntax_key(syntaxes: &[Rc<ValidationToken>]) -> Option<String> {
99    let node = SYNTAX_NODES.with(|n| n.borrow().get(&(syntaxes.as_ptr() as usize)).copied())?;
100    NODE_KEYS.with(|k| k.get(&node).cloned())
101}
102
103/// true if a type or a function syntax is defined
104pub fn has_syntax(key: &str) -> bool {
105    if let Some(defined) = DEFINED_SYNTAXES.with(|d| d.borrow().get(key).copied()) {
106        return defined;
107    }
108    let defined = lookup_node(ValidationSyntaxGroupEnum::Syntaxes, key).is_some();
109    DEFINED_SYNTAXES.with(|d| d.borrow_mut().insert(key.to_string(), defined));
110    defined
111}
112
113/// the raw syntax of a type or a function
114pub fn get_syntax(key: &str) -> Option<&'static str> {
115    lookup_node(ValidationSyntaxGroupEnum::Syntaxes, key).and_then(|n| n["syntax"].as_str())
116}
117
118/// `^(@?)(-[a-zA-Z]+)-(.*?)$`: the name without its vendor prefix
119fn strip_vendor_prefix(key: &str) -> Option<String> {
120    let (at, rest) = match key.strip_prefix('@') {
121        Some(rest) => ("@", rest),
122        None => ("", key),
123    };
124    let rest = rest.strip_prefix('-')?;
125    let letters = rest.bytes().take_while(|b| b.is_ascii_alphabetic()).count();
126    if letters == 0 {
127        return None;
128    }
129    let tail = rest[letters..].strip_prefix('-')?;
130    Some(format!("{}{}", at, tail))
131}
132
133fn find_node(group: ValidationSyntaxGroupEnum, key: &str) -> Option<&'static serde_json::Value> {
134    if let Some(node) = lookup_node(group, key) {
135        return Some(node);
136    }
137    let mut key = key.to_string();
138    if key.starts_with('@') || key.starts_with('-') {
139        if let Some(stripped) = strip_vendor_prefix(&key) {
140            key = stripped;
141        }
142    }
143    lookup_node(group, &key)
144}
145
146/// parsed syntax of a definition, shared by the names that share the definition
147pub fn get_parsed_syntax(group: ValidationSyntaxGroupEnum, key: &str) -> Option<Rc<Vec<Rc<ValidationToken>>>> {
148    if let Some(cached) = PARSED_BY_KEY.with(|c| c.borrow()[group as usize].get(key).cloned()) {
149        return cached;
150    }
151    let result = find_node(group, key).map(|node| {
152        let id = node as *const serde_json::Value as usize;
153        if let Some(parsed) = PARSED_SYNTAXES.with(|p| p.borrow().get(&id).cloned()) {
154            return parsed;
155        }
156        let mut tokens = parse_syntax(node["syntax"].as_str().unwrap_or(""));
157        trim_syntax_array(&mut tokens);
158        let parsed = Rc::new(tokens);
159        PARSED_SYNTAXES.with(|p| p.borrow_mut().insert(id, parsed.clone()));
160        SYNTAX_NODES.with(|n| n.borrow_mut().insert(parsed.as_ptr() as usize, id));
161        parsed
162    });
163    PARSED_BY_KEY.with(|c| c.borrow_mut()[group as usize].insert(Box::from(key), result.clone()));
164    result
165}
166
167/// syntax rule of an at-rule: its prelude, its block, its descriptors
168pub fn get_syntax_rule(group: ValidationSyntaxGroupEnum, key: &str) -> Option<Rc<ValidationSyntaxRule>> {
169    if let Some(cached) = SYNTAX_RULES.with(|c| c.borrow()[group as usize].get(key).cloned()) {
170        return cached;
171    }
172    let result = compute_syntax_rule(group, key).map(Rc::new);
173    SYNTAX_RULES.with(|c| c.borrow_mut()[group as usize].insert(Box::from(key), result.clone()));
174    result
175}
176
177fn compute_syntax_rule(group: ValidationSyntaxGroupEnum, key: &str) -> Option<ValidationSyntaxRule> {
178    let node = find_node(group, key)?;
179    let syntax_rules = get_parsed_syntax(group, key)?;
180    let mut block_start: Option<usize> = None;
181    let mut block_end: Option<usize> = None;
182    for (i, t) in syntax_rules.iter().enumerate() {
183        if t.typ == V::OpenCurlyBrace || t.typ == V::SemiColon {
184            block_start = Some(i);
185            break;
186        }
187    }
188    if block_start.is_some() {
189        for i in (0..syntax_rules.len()).rev() {
190            if syntax_rules[i].typ == V::CloseCurlyBrace {
191                block_end = Some(i);
192                break;
193            }
194        }
195    }
196    // `slice(blockStart + 1, blockEnd)`: blockEnd -1 slices to the last but one token
197    let mut block: Option<Vec<Rc<ValidationToken>>> = block_start.map(|start| {
198        let end = match block_end {
199            Some(end) => end,
200            None => syntax_rules.len().saturating_sub(1),
201        };
202        let mut b = if start + 1 <= end { syntax_rules[start + 1..end].to_vec() } else { Vec::new() };
203        trim_syntax_array(&mut b);
204        b
205    });
206    let mut prelude: Vec<Rc<ValidationToken>> = match block_start {
207        None => syntax_rules.to_vec(),
208        Some(start) => syntax_rules[..start].to_vec(),
209    };
210    trim_syntax_array(&mut prelude);
211    let property_descriptors = node.get("descriptors").and_then(|d| d.as_object()).map(|descriptors| {
212        let mut map = HashMap::default();
213        for (key, value) in descriptors {
214            let syntax = value.as_str().or_else(|| value["syntax"].as_str()).unwrap_or("");
215            map.insert(key.clone(), Rc::new(parse_syntax(syntax)));
216        }
217        Rc::new(map)
218    });
219    let mut optional_body = false;
220    if block.as_ref().is_none_or(|b| b.is_empty()) && !prelude.is_empty() {
221        let mut k = prelude.len() as isize - 1;
222        if prelude[k as usize].typ == V::SemiColon {
223            k -= 1;
224        }
225        if k >= 0 && prelude[k as usize].typ == V::Bracket {
226            let chi = prelude[k as usize].children();
227            if chi.first().is_some_and(|c| c.typ == V::OpenCurlyBrace) && chi.last().is_some_and(|c| c.typ == V::CloseCurlyBrace) {
228                block = Some(chi[1..chi.len() - 1].to_vec());
229                optional_body = prelude[k as usize].is_optional();
230            }
231        }
232    }
233    let syntax = node["syntax"].as_str().unwrap_or("");
234    Some(ValidationSyntaxRule {
235        optional_body,
236        accept_any_declaration: syntax.contains("<declaration-list>"),
237        accept_any_rule: syntax.contains("<group-rule-body>") || syntax.contains("<stylesheet>"),
238        prelude: Rc::new(prelude),
239        block: block.map(Rc::new),
240        property_descriptors,
241    })
242}