Skip to main content

rust_css_parser/
options.rs

1//! Port of the option interfaces of `src/@types/index.d.ts` (`ParserOptions`, `ParserSyncOptions`, `MinifyOptions`,
2//! `ValidationOptions`, `RenderOptions`, `ModuleSyncOptions`, ...).
3//!
4//! The typescript options object is shared and mutated by the parser (`source`, `parseInfo`, `sourcesMap`, ...): the
5//! port keeps a single struct passed by reference. Host callbacks (loaders, visitors, scoped name generators) are
6//! defined in [`crate::host`].
7
8use crate::ast::types::MergeRulesEnum;
9use crate::parser::source::SourceFile;
10use std::cell::RefCell;
11use std::rc::Rc;
12
13/// sources of a parse, by id, in insertion order (`Map` in typescript)
14#[derive(Default, Debug)]
15pub struct Sources {
16    entries: Vec<(u32, Rc<SourceFile>)>,
17}
18
19impl Sources {
20    pub fn get(&self, id: u32) -> Option<Rc<SourceFile>> {
21        self.entries.iter().find(|(k, _)| *k == id).map(|(_, v)| v.clone())
22    }
23
24    /// `map.set(id, source)`: replaced in place when the id exists
25    pub fn insert(&mut self, id: u32, source: Rc<SourceFile>) {
26        match self.entries.iter_mut().find(|(k, _)| *k == id) {
27            Some(entry) => entry.1 = source,
28            None => self.entries.push((id, source)),
29        }
30    }
31
32    pub fn iter(&self) -> impl Iterator<Item = &(u32, Rc<SourceFile>)> {
33        self.entries.iter()
34    }
35}
36
37/// sources of a parse: shared by the copies of the options
38pub type SourcesMap = Rc<RefCell<Sources>>;
39
40/// `removeDuplicateDeclarations?: boolean | string | string[]`
41#[derive(Clone, Debug, PartialEq)]
42pub enum RemoveDuplicateDeclarations {
43    Bool(bool),
44    Names(Vec<String>),
45}
46
47/// `sourcemap?: boolean | "inline"`
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49pub enum SourceMapOption {
50    Off,
51    On,
52    Inline,
53}
54
55/// `module?: boolean | ModuleCaseTransformEnum | ModuleScopeEnumOptions | ModuleSyncOptions`
56#[derive(Clone, Debug, PartialEq)]
57pub enum ModuleOption {
58    Bool(bool),
59    Flags(u32),
60    Options(ModuleOptions),
61}
62
63/// `scoped?: boolean | ModuleScopeEnumOptions`
64#[derive(Clone, Copy, Debug, PartialEq)]
65pub enum ModuleScoped {
66    Bool(bool),
67    Flags(u32),
68}
69
70/// `ModuleSyncOptions` / `ModuleAsyncOptions`
71#[derive(Clone, Debug, Default, PartialEq)]
72pub struct ModuleOptions {
73    pub scoped: Option<ModuleScoped>,
74    pub file_path: Option<String>,
75    pub hash_length: Option<u32>,
76    pub pattern: Option<String>,
77    pub naming: Option<u32>,
78    /// host callback id of `generateScopedName`
79    pub generate_scoped_name: Option<u32>,
80}
81
82/// `convertColor?: boolean | ColorType`
83#[derive(Clone, Copy, Debug, PartialEq)]
84pub enum ConvertColor {
85    Bool(bool),
86    Type(u8),
87}
88
89/// parser, validation and minification options
90#[derive(Clone, Default)]
91pub struct ParserOptions {
92    // MinifyOptions
93    pub minify: Option<bool>,
94    pub minify_ast: Option<bool>,
95    pub parse_color: Option<bool>,
96    pub nesting_rules: Option<bool>,
97    pub remove_duplicate_declarations: Option<RemoveDuplicateDeclarations>,
98    pub compute_shorthand: Option<bool>,
99    pub compute_transform: Option<bool>,
100    pub compute_calc_expression: Option<bool>,
101    pub inline_css_variables: Option<bool>,
102    pub evaluate_mixins: Option<bool>,
103    pub keep_mixins: Option<bool>,
104    pub remove_empty: Option<bool>,
105    pub remove_prefix: Option<bool>,
106    /// optimize the selectors (reduce, factor with `:is()`): `None` is `true`
107    pub optimize_selectors: Option<bool>,
108    /// `mergeRules?: boolean | MergeRulesEnum`: a `MergeRulesEnum` value (`true` is `All`, `false` is `None`). `None`
109    /// (unset): `All` when the ast is minified, no merge otherwise
110    pub merge_rules: Option<u32>,
111    /// the inexpensive minifications only: sets the default value of the fast mode settings (see `with_defaults()`)
112    pub fast_mode: Option<bool>,
113    pub pass: Option<u32>,
114    // ParserSourceMapOptions
115    pub sourcemap: Option<SourceMapOption>,
116    pub input_source_map: Option<String>,
117    // ValidationOptions
118    pub nested_rule: Option<bool>,
119    pub validation: Option<bool>,
120    pub lenient: Option<bool>,
121    /// the restrictions of the typescript `parseSync()` / `transformSync()`, set by the javascript bindings only: the
122    /// `@import` rules are not resolved, the visitor results are not awaited, a css variable import or a `composes`
123    /// from a file is an error, the scoped names are generated by `generateSyncScopedName()`. the rust api has no
124    /// restriction: `do_parse()` and `do_parse_sync()` provide every feature
125    pub sync_api_compat: bool,
126    pub is_optional: Option<bool>,
127    pub is_repeatable: Option<bool>,
128    pub is_list: Option<bool>,
129    pub occurrence: Option<bool>,
130    pub at_least_once: Option<bool>,
131    // ParseSourceOptions
132    pub sources_map: Option<SourcesMap>,
133    pub source: Option<Rc<SourceFile>>,
134    // ParserSyncOptions
135    pub src: Option<String>,
136    pub remove_charset: Option<bool>,
137    pub cwd: Option<String>,
138    pub expand_nesting_rules: Option<bool>,
139    pub expand_if_syntax: Option<bool>,
140    pub resolve_urls: Option<bool>,
141    pub set_parent: Option<bool>,
142    pub module: Option<ModuleOption>,
143    // ParserOptions
144    pub resolve_import: Option<bool>,
145    /// visitor maps (`visitor`), with the functions replaced by host callback ids
146    pub visitor: Option<Rc<crate::host::HostDef>>,
147    /// host callback id of `load`
148    pub load: Option<u32>,
149    /// host callback id of the reader of a stream input: it returns the next chunk (bytes or text), `null` at the end
150    /// of the stream. the bindings set it when the input is a `ReadableStream`
151    pub stream: Option<u32>,
152    /// the size of the css of the stream, in bytes, when it is known (a file, a response with a content length): the
153    /// code units and the arena are allocated once. 0: not known
154    pub stream_size: Option<usize>,
155    // RenderOptions
156    pub minify_values: Option<bool>,
157    pub beautify: Option<bool>,
158    pub preserve_license: Option<bool>,
159    pub indent: Option<String>,
160    pub new_line: Option<String>,
161    pub remove_comments: Option<bool>,
162    pub convert_color: Option<ConvertColor>,
163    pub with_parents: Option<bool>,
164    pub output: Option<String>,
165}
166
167impl ParserOptions {
168    #[inline]
169    pub fn is(&self, value: Option<bool>) -> bool {
170        value == Some(true)
171    }
172
173    /// `options.validation` is truthy
174    pub fn validation(&self) -> bool {
175        self.validation == Some(true)
176    }
177}
178
179use crate::host::HostDef;
180
181/// truthiness of a javascript value (`!!value`)
182fn truthy(def: &HostDef) -> bool {
183    match def {
184        HostDef::Null => false,
185        HostDef::Bool(b) => *b,
186        HostDef::Number(n) => *n != 0.0 && !n.is_nan(),
187        HostDef::Str(s) => !s.is_empty(),
188        _ => true,
189    }
190}
191
192impl ParserOptions {
193    /// the options of a javascript options object. the keys are the typescript option names; `undefined` and `null`
194    /// values are absent options. the functions are host callbacks
195    pub fn from_host(def: &HostDef) -> ParserOptions {
196        let mut o = ParserOptions::default();
197        for (key, value) in def.entries() {
198            if matches!(value, HostDef::Null) {
199                continue;
200            }
201            let b = || Some(truthy(&value));
202            let s = || match &value {
203                HostDef::Str(s) => Some(s.to_string()),
204                HostDef::Number(n) => Some(crate::utils::number::js_number_to_string(*n)),
205                _ => None,
206            };
207            let n = || match &value {
208                HostDef::Number(n) => Some(*n),
209                _ => None,
210            };
211            match &*key {
212                "minify" => o.minify = b(),
213                "minifyAST" => o.minify_ast = b(),
214                "parseColor" => o.parse_color = b(),
215                "nestingRules" => o.nesting_rules = b(),
216                "removeDuplicateDeclarations" => {
217                    o.remove_duplicate_declarations = Some(match &value {
218                        HostDef::Str(s) => RemoveDuplicateDeclarations::Names(vec![s.to_string()]),
219                        HostDef::Array(items) => RemoveDuplicateDeclarations::Names(
220                            items.iter().filter_map(|i| if let HostDef::Str(s) = i { Some(s.to_string()) } else { None }).collect(),
221                        ),
222                        other => RemoveDuplicateDeclarations::Bool(truthy(other)),
223                    })
224                }
225                "computeShorthand" => o.compute_shorthand = b(),
226                "computeTransform" => o.compute_transform = b(),
227                "computeCalcExpression" => o.compute_calc_expression = b(),
228                "inlineCssVariables" => o.inline_css_variables = b(),
229                "evaluateMixins" => o.evaluate_mixins = b(),
230                "keepMixins" => o.keep_mixins = b(),
231                "removeEmpty" => o.remove_empty = b(),
232                "removePrefix" => o.remove_prefix = b(),
233                "optimizeSelectors" => o.optimize_selectors = b(),
234                "mergeRules" => {
235                    // `boolean | MergeRulesEnum`: `true` is `All`, `false` is `None`
236                    o.merge_rules = Some(match n() {
237                        Some(n) => n as u32,
238                        None if truthy(&value) => MergeRulesEnum::All,
239                        None => MergeRulesEnum::None,
240                    })
241                }
242                "fastMode" => o.fast_mode = b(),
243                "pass" => o.pass = n().map(|n| n as u32),
244                "sourcemap" => {
245                    o.sourcemap = Some(match &value {
246                        HostDef::Str(s) if &**s == "inline" => SourceMapOption::Inline,
247                        other if truthy(other) => SourceMapOption::On,
248                        _ => SourceMapOption::Off,
249                    })
250                }
251                "inputSourceMap" => {
252                    o.input_source_map = match &value {
253                        HostDef::Str(s) => Some(s.to_string()),
254                        other => Some(crate::plain::Plain::from_host_def(other).to_json()),
255                    }
256                }
257                "nestedRule" => o.nested_rule = b(),
258                "validation" => o.validation = b(),
259                "lenient" => o.lenient = b(),
260                "isOptional" => o.is_optional = b(),
261                "isRepeatable" => o.is_repeatable = b(),
262                "isList" => o.is_list = b(),
263                "occurrence" => o.occurrence = b(),
264                "atLeastOnce" => o.at_least_once = b(),
265                "src" => o.src = s(),
266                "removeCharset" => o.remove_charset = b(),
267                "cwd" => o.cwd = s(),
268                "expandNestingRules" => o.expand_nesting_rules = b(),
269                "expandIfSyntax" => o.expand_if_syntax = b(),
270                "resolveUrls" => o.resolve_urls = b(),
271                "setParent" => o.set_parent = b(),
272                "module" => {
273                    o.module = Some(match &value {
274                        HostDef::Number(n) => ModuleOption::Flags(*n as u32),
275                        HostDef::Object(_) => {
276                            let mut m = ModuleOptions::default();
277                            for (k, v) in value.entries() {
278                                match (&*k, &v) {
279                                    ("scoped", HostDef::Number(n)) => m.scoped = Some(ModuleScoped::Flags(*n as u32)),
280                                    ("scoped", HostDef::Null) => {}
281                                    ("scoped", other) => m.scoped = Some(ModuleScoped::Bool(truthy(other))),
282                                    ("filePath", HostDef::Str(s)) => m.file_path = Some(s.to_string()),
283                                    ("hashLength", HostDef::Number(n)) => m.hash_length = Some(*n as u32),
284                                    ("pattern", HostDef::Str(s)) => m.pattern = Some(s.to_string()),
285                                    ("naming", HostDef::Number(n)) => m.naming = Some(*n as u32),
286                                    ("generateScopedName", HostDef::Fn { id, .. }) => m.generate_scoped_name = Some(*id),
287                                    _ => {}
288                                }
289                            }
290                            ModuleOption::Options(m)
291                        }
292                        other => ModuleOption::Bool(truthy(other)),
293                    })
294                }
295                "resolveImport" => o.resolve_import = b(),
296                "visitor" => o.visitor = Some(Rc::new(value.clone())),
297                "load" => {
298                    if let HostDef::Fn { id, .. } = &value {
299                        o.load = Some(*id)
300                    }
301                }
302                "stream" => {
303                    if let HostDef::Fn { id, .. } = &value {
304                        o.stream = Some(*id)
305                    }
306                }
307                "streamSize" => o.stream_size = n().filter(|n| *n > 0.0).map(|n| n as usize),
308                "minifyValues" => o.minify_values = b(),
309                "beautify" => o.beautify = b(),
310                "preserveLicense" => o.preserve_license = b(),
311                "indent" => o.indent = s(),
312                "newLine" => o.new_line = s(),
313                "removeComments" => o.remove_comments = b(),
314                "convertColor" => {
315                    o.convert_color = Some(match &value {
316                        HostDef::Number(n) => ConvertColor::Type(*n as u8),
317                        HostDef::Str(name) => ConvertColor::Type(crate::ast::types::ColorType::value(&name.to_uppercase().replace('-', "_")).unwrap_or(0)),
318                        other => ConvertColor::Bool(truthy(other)),
319                    })
320                }
321                "withParents" => o.with_parents = b(),
322                "output" => o.output = s(),
323                _ => {}
324            }
325        }
326        o
327    }
328}