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