rust-css-parser 2.3.2

Fault-tolerant CSS parser, validator, minifier and renderer: the Rust port of @tbela99/css-parser
Documentation
//! Port of the option interfaces of `src/@types/index.d.ts` (`ParserOptions`, `ParserSyncOptions`, `MinifyOptions`,
//! `ValidationOptions`, `RenderOptions`, `ModuleSyncOptions`, ...).
//!
//! The typescript options object is shared and mutated by the parser (`source`, `parseInfo`, `sourcesMap`, ...): the
//! port keeps a single struct passed by reference. Host callbacks (loaders, visitors, scoped name generators) are
//! defined in [`crate::host`].

use crate::ast::types::MergeRulesEnum;
use crate::parser::source::SourceFile;
use std::cell::RefCell;
use std::rc::Rc;

/// sources of a parse, by id, in insertion order (`Map` in typescript)
#[derive(Default, Debug)]
pub struct Sources {
    entries: Vec<(u32, Rc<SourceFile>)>,
}

impl Sources {
    pub fn get(&self, id: u32) -> Option<Rc<SourceFile>> {
        self.entries.iter().find(|(k, _)| *k == id).map(|(_, v)| v.clone())
    }

    /// `map.set(id, source)`: replaced in place when the id exists
    pub fn insert(&mut self, id: u32, source: Rc<SourceFile>) {
        match self.entries.iter_mut().find(|(k, _)| *k == id) {
            Some(entry) => entry.1 = source,
            None => self.entries.push((id, source)),
        }
    }

    pub fn iter(&self) -> impl Iterator<Item = &(u32, Rc<SourceFile>)> {
        self.entries.iter()
    }
}

/// sources of a parse: shared by the copies of the options
pub type SourcesMap = Rc<RefCell<Sources>>;

/// `removeDuplicateDeclarations?: boolean | string | string[]`
#[derive(Clone, Debug, PartialEq)]
pub enum RemoveDuplicateDeclarations {
    Bool(bool),
    Names(Vec<String>),
}

/// `sourcemap?: boolean | "inline"`
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SourceMapOption {
    Off,
    On,
    Inline,
}

/// `module?: boolean | ModuleCaseTransformEnum | ModuleScopeEnumOptions | ModuleSyncOptions`
#[derive(Clone, Debug, PartialEq)]
pub enum ModuleOption {
    Bool(bool),
    Flags(u32),
    Options(ModuleOptions),
}

/// `scoped?: boolean | ModuleScopeEnumOptions`
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ModuleScoped {
    Bool(bool),
    Flags(u32),
}

/// `ModuleSyncOptions` / `ModuleAsyncOptions`
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ModuleOptions {
    pub scoped: Option<ModuleScoped>,
    pub file_path: Option<String>,
    pub hash_length: Option<u32>,
    pub pattern: Option<String>,
    pub naming: Option<u32>,
    /// host callback id of `generateScopedName`
    pub generate_scoped_name: Option<u32>,
}

/// `convertColor?: boolean | ColorType`
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ConvertColor {
    Bool(bool),
    Type(u8),
}

/// parser, validation and minification options
#[derive(Clone, Default)]
pub struct ParserOptions {
    // MinifyOptions
    pub minify: Option<bool>,
    pub minify_ast: Option<bool>,
    pub parse_color: Option<bool>,
    pub nesting_rules: Option<bool>,
    pub remove_duplicate_declarations: Option<RemoveDuplicateDeclarations>,
    pub compute_shorthand: Option<bool>,
    pub compute_transform: Option<bool>,
    pub compute_calc_expression: Option<bool>,
    pub inline_css_variables: Option<bool>,
    pub evaluate_mixins: Option<bool>,
    pub keep_mixins: Option<bool>,
    pub remove_empty: Option<bool>,
    pub remove_prefix: Option<bool>,
    /// optimize the selectors (reduce, factor with `:is()`): `None` is `true`
    pub optimize_selectors: Option<bool>,
    /// `mergeRules?: boolean | MergeRulesEnum`: a `MergeRulesEnum` value (`true` is `All`, `false` is `None`). `None`
    /// (unset): `All` when the ast is minified, no merge otherwise
    pub merge_rules: Option<u32>,
    /// the inexpensive minifications only: sets the default value of the fast mode settings (see `with_defaults()`)
    pub fast_mode: Option<bool>,
    pub pass: Option<u32>,
    // ParserSourceMapOptions
    pub sourcemap: Option<SourceMapOption>,
    pub input_source_map: Option<String>,
    // ValidationOptions
    pub nested_rule: Option<bool>,
    pub validation: Option<bool>,
    pub lenient: Option<bool>,
    /// the restrictions of the typescript `parseSync()` / `transformSync()`, set by the javascript bindings only: the
    /// `@import` rules are not resolved, the visitor results are not awaited, a css variable import or a `composes`
    /// from a file is an error, the scoped names are generated by `generateSyncScopedName()`. the rust api has no
    /// restriction: `do_parse()` and `do_parse_sync()` provide every feature
    pub sync_api_compat: bool,
    pub is_optional: Option<bool>,
    pub is_repeatable: Option<bool>,
    pub is_list: Option<bool>,
    pub occurrence: Option<bool>,
    pub at_least_once: Option<bool>,
    // ParseSourceOptions
    pub sources_map: Option<SourcesMap>,
    pub source: Option<Rc<SourceFile>>,
    // ParserSyncOptions
    pub src: Option<String>,
    pub remove_charset: Option<bool>,
    pub cwd: Option<String>,
    pub expand_nesting_rules: Option<bool>,
    pub expand_if_syntax: Option<bool>,
    pub resolve_urls: Option<bool>,
    pub set_parent: Option<bool>,
    pub module: Option<ModuleOption>,
    // ParserOptions
    pub resolve_import: Option<bool>,
    /// visitor maps (`visitor`), with the functions replaced by host callback ids
    pub visitor: Option<Rc<crate::host::HostDef>>,
    /// host callback id of `load`
    pub load: Option<u32>,
    /// host callback id of the reader of a stream input: it returns the next chunk (bytes or text), `null` at the end
    /// of the stream. the bindings set it when the input is a `ReadableStream`
    pub stream: Option<u32>,
    /// the size of the css of the stream, in bytes, when it is known (a file, a response with a content length): the
    /// code units and the arena are allocated once. 0: not known
    pub stream_size: Option<usize>,
    // RenderOptions
    pub minify_values: Option<bool>,
    pub beautify: Option<bool>,
    pub preserve_license: Option<bool>,
    pub indent: Option<String>,
    pub new_line: Option<String>,
    pub remove_comments: Option<bool>,
    pub convert_color: Option<ConvertColor>,
    pub with_parents: Option<bool>,
    pub output: Option<String>,
}

impl ParserOptions {
    #[inline]
    pub fn is(&self, value: Option<bool>) -> bool {
        value == Some(true)
    }

    /// `options.validation` is truthy
    pub fn validation(&self) -> bool {
        self.validation == Some(true)
    }
}

use crate::host::HostDef;

/// truthiness of a javascript value (`!!value`)
fn truthy(def: &HostDef) -> bool {
    match def {
        HostDef::Null => false,
        HostDef::Bool(b) => *b,
        HostDef::Number(n) => *n != 0.0 && !n.is_nan(),
        HostDef::Str(s) => !s.is_empty(),
        _ => true,
    }
}

impl ParserOptions {
    /// the options of a javascript options object. the keys are the typescript option names; `undefined` and `null`
    /// values are absent options. the functions are host callbacks
    pub fn from_host(def: &HostDef) -> ParserOptions {
        let mut o = ParserOptions::default();
        for (key, value) in def.entries() {
            if matches!(value, HostDef::Null) {
                continue;
            }
            let b = || Some(truthy(&value));
            let s = || match &value {
                HostDef::Str(s) => Some(s.to_string()),
                HostDef::Number(n) => Some(crate::utils::number::js_number_to_string(*n)),
                _ => None,
            };
            let n = || match &value {
                HostDef::Number(n) => Some(*n),
                _ => None,
            };
            match &*key {
                "minify" => o.minify = b(),
                "minifyAST" => o.minify_ast = b(),
                "parseColor" => o.parse_color = b(),
                "nestingRules" => o.nesting_rules = b(),
                "removeDuplicateDeclarations" => {
                    o.remove_duplicate_declarations = Some(match &value {
                        HostDef::Str(s) => RemoveDuplicateDeclarations::Names(vec![s.to_string()]),
                        HostDef::Array(items) => RemoveDuplicateDeclarations::Names(
                            items.iter().filter_map(|i| if let HostDef::Str(s) = i { Some(s.to_string()) } else { None }).collect(),
                        ),
                        other => RemoveDuplicateDeclarations::Bool(truthy(other)),
                    })
                }
                "computeShorthand" => o.compute_shorthand = b(),
                "computeTransform" => o.compute_transform = b(),
                "computeCalcExpression" => o.compute_calc_expression = b(),
                "inlineCssVariables" => o.inline_css_variables = b(),
                "evaluateMixins" => o.evaluate_mixins = b(),
                "keepMixins" => o.keep_mixins = b(),
                "removeEmpty" => o.remove_empty = b(),
                "removePrefix" => o.remove_prefix = b(),
                "optimizeSelectors" => o.optimize_selectors = b(),
                "mergeRules" => {
                    // `boolean | MergeRulesEnum`: `true` is `All`, `false` is `None`
                    o.merge_rules = Some(match n() {
                        Some(n) => n as u32,
                        None if truthy(&value) => MergeRulesEnum::All,
                        None => MergeRulesEnum::None,
                    })
                }
                "fastMode" => o.fast_mode = b(),
                "pass" => o.pass = n().map(|n| n as u32),
                "sourcemap" => {
                    o.sourcemap = Some(match &value {
                        HostDef::Str(s) if &**s == "inline" => SourceMapOption::Inline,
                        other if truthy(other) => SourceMapOption::On,
                        _ => SourceMapOption::Off,
                    })
                }
                "inputSourceMap" => {
                    o.input_source_map = match &value {
                        HostDef::Str(s) => Some(s.to_string()),
                        other => Some(crate::plain::Plain::from_host_def(other).to_json()),
                    }
                }
                "nestedRule" => o.nested_rule = b(),
                "validation" => o.validation = b(),
                "lenient" => o.lenient = b(),
                "isOptional" => o.is_optional = b(),
                "isRepeatable" => o.is_repeatable = b(),
                "isList" => o.is_list = b(),
                "occurrence" => o.occurrence = b(),
                "atLeastOnce" => o.at_least_once = b(),
                "src" => o.src = s(),
                "removeCharset" => o.remove_charset = b(),
                "cwd" => o.cwd = s(),
                "expandNestingRules" => o.expand_nesting_rules = b(),
                "expandIfSyntax" => o.expand_if_syntax = b(),
                "resolveUrls" => o.resolve_urls = b(),
                "setParent" => o.set_parent = b(),
                "module" => {
                    o.module = Some(match &value {
                        HostDef::Number(n) => ModuleOption::Flags(*n as u32),
                        HostDef::Object(_) => {
                            let mut m = ModuleOptions::default();
                            for (k, v) in value.entries() {
                                match (&*k, &v) {
                                    ("scoped", HostDef::Number(n)) => m.scoped = Some(ModuleScoped::Flags(*n as u32)),
                                    ("scoped", HostDef::Null) => {}
                                    ("scoped", other) => m.scoped = Some(ModuleScoped::Bool(truthy(other))),
                                    ("filePath", HostDef::Str(s)) => m.file_path = Some(s.to_string()),
                                    ("hashLength", HostDef::Number(n)) => m.hash_length = Some(*n as u32),
                                    ("pattern", HostDef::Str(s)) => m.pattern = Some(s.to_string()),
                                    ("naming", HostDef::Number(n)) => m.naming = Some(*n as u32),
                                    ("generateScopedName", HostDef::Fn { id, .. }) => m.generate_scoped_name = Some(*id),
                                    _ => {}
                                }
                            }
                            ModuleOption::Options(m)
                        }
                        other => ModuleOption::Bool(truthy(other)),
                    })
                }
                "resolveImport" => o.resolve_import = b(),
                "visitor" => o.visitor = Some(Rc::new(value.clone())),
                "load" => {
                    if let HostDef::Fn { id, .. } = &value {
                        o.load = Some(*id)
                    }
                }
                "stream" => {
                    if let HostDef::Fn { id, .. } = &value {
                        o.stream = Some(*id)
                    }
                }
                "streamSize" => o.stream_size = n().filter(|n| *n > 0.0).map(|n| n as usize),
                "minifyValues" => o.minify_values = b(),
                "beautify" => o.beautify = b(),
                "preserveLicense" => o.preserve_license = b(),
                "indent" => o.indent = s(),
                "newLine" => o.new_line = s(),
                "removeComments" => o.remove_comments = b(),
                "convertColor" => {
                    o.convert_color = Some(match &value {
                        HostDef::Number(n) => ConvertColor::Type(*n as u8),
                        HostDef::Str(name) => ConvertColor::Type(crate::ast::types::ColorType::value(&name.to_uppercase().replace('-', "_")).unwrap_or(0)),
                        other => ConvertColor::Bool(truthy(other)),
                    })
                }
                "withParents" => o.with_parents = b(),
                "output" => o.output = s(),
                _ => {}
            }
        }
        o
    }
}