use crate::ast::types::MergeRulesEnum;
use crate::parser::source::SourceFile;
use std::cell::RefCell;
use std::rc::Rc;
#[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())
}
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()
}
}
pub type SourcesMap = Rc<RefCell<Sources>>;
#[derive(Clone, Debug, PartialEq)]
pub enum RemoveDuplicateDeclarations {
Bool(bool),
Names(Vec<String>),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SourceMapOption {
Off,
On,
Inline,
}
#[derive(Clone, Debug, PartialEq)]
pub enum ModuleOption {
Bool(bool),
Flags(u32),
Options(ModuleOptions),
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ModuleScoped {
Bool(bool),
Flags(u32),
}
#[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>,
pub generate_scoped_name: Option<u32>,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ConvertColor {
Bool(bool),
Type(u8),
}
#[derive(Clone, Default)]
pub struct ParserOptions {
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>,
pub optimize_selectors: Option<bool>,
pub merge_rules: Option<u32>,
pub fast_mode: Option<bool>,
pub pass: Option<u32>,
pub sourcemap: Option<SourceMapOption>,
pub input_source_map: Option<String>,
pub nested_rule: Option<bool>,
pub validation: Option<bool>,
pub lenient: Option<bool>,
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>,
pub sources_map: Option<SourcesMap>,
pub source: Option<Rc<SourceFile>>,
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>,
pub resolve_import: Option<bool>,
pub visitor: Option<Rc<crate::host::HostDef>>,
pub load: Option<u32>,
pub stream: Option<u32>,
pub stream_size: Option<usize>,
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)
}
pub fn validation(&self) -> bool {
self.validation == Some(true)
}
}
use crate::host::HostDef;
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 {
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" => {
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
}
}