use std::collections::{BTreeMap, HashMap};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImportInfo {
pub name: String,
pub source: String,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ForeignTypeAlias {
pub name: String,
pub from: String,
}
pub const FOREIGN_HANDLERS_MODULE: &str = "#macroforge/config";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ForeignHandler {
Encode,
Decode,
Default,
HasShape,
Is,
Clone,
ToString,
Equals,
HashCode,
PartialCompare,
Compare,
}
impl ForeignHandler {
pub const ALL: [Self; 11] = [
Self::Encode,
Self::Decode,
Self::Default,
Self::HasShape,
Self::Is,
Self::Clone,
Self::ToString,
Self::Equals,
Self::HashCode,
Self::PartialCompare,
Self::Compare,
];
pub fn key(self) -> &'static str {
match self {
Self::Encode => "encode",
Self::Decode => "decode",
Self::Default => "default",
Self::HasShape => "hasShape",
Self::Is => "is",
Self::Clone => "clone",
Self::ToString => "toString",
Self::Equals => "equals",
Self::HashCode => "hashCode",
Self::PartialCompare => "partialCompare",
Self::Compare => "compare",
}
}
pub fn from_key(key: &str) -> Option<Self> {
Self::ALL.into_iter().find(|handler| handler.key() == key)
}
fn suffix(self) -> &'static str {
match self {
Self::Encode => "Encode",
Self::Decode => "Decode",
Self::Default => "Default",
Self::HasShape => "HasShape",
Self::Is => "Is",
Self::Clone => "Clone",
Self::ToString => "ToString",
Self::Equals => "Equals",
Self::HashCode => "HashCode",
Self::PartialCompare => "PartialCompare",
Self::Compare => "Compare",
}
}
pub fn export_name(self, type_name: &str) -> String {
format!("__foreign__{}{}", camel_type_name(type_name), self.suffix())
}
}
fn camel_type_name(name: &str) -> String {
let mut camel = String::with_capacity(name.len());
for (index, segment) in name.split('.').enumerate() {
if index > 0 {
camel.push_str(segment);
continue;
}
let chars: Vec<char> = segment.chars().collect();
let capitals = chars.iter().take_while(|c| c.is_uppercase()).count();
let lowered = if capitals == chars.len() || capitals <= 1 {
capitals
} else {
capitals - 1
};
for (position, c) in chars.into_iter().enumerate() {
if position < lowered.max(1) {
camel.extend(c.to_lowercase());
} else {
camel.push(c);
}
}
}
camel
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HandlerSite {
pub handler: ForeignHandler,
pub module: std::path::PathBuf,
pub start: u32,
pub end: u32,
pub identifier: Option<String>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ForeignTypeConfig {
pub name: String,
pub from: Vec<String>,
pub encode_expr: Option<String>,
pub decode_expr: Option<String>,
pub default_expr: Option<String>,
pub has_shape_expr: Option<String>,
#[serde(default)]
pub is_expr: Option<String>,
#[serde(default)]
pub clone_expr: Option<String>,
#[serde(default)]
pub to_string_expr: Option<String>,
#[serde(default)]
pub equals_expr: Option<String>,
#[serde(default)]
pub hash_code_expr: Option<String>,
#[serde(default)]
pub partial_compare_expr: Option<String>,
#[serde(default)]
pub compare_expr: Option<String>,
#[serde(default)]
pub aliases: Vec<ForeignTypeAlias>,
#[serde(default)]
pub builtin: bool,
#[serde(skip)]
pub handler_sites: Vec<HandlerSite>,
}
impl ForeignTypeConfig {
pub fn get_namespace(&self) -> Option<&str> {
self.name.rsplit_once('.').map(|(namespace, _)| namespace)
}
pub fn get_type_name(&self) -> &str {
self.name.rsplit('.').next().unwrap_or(&self.name)
}
pub fn handler_expr_mut(&mut self, handler: ForeignHandler) -> &mut Option<String> {
match handler {
ForeignHandler::Encode => &mut self.encode_expr,
ForeignHandler::Decode => &mut self.decode_expr,
ForeignHandler::Default => &mut self.default_expr,
ForeignHandler::HasShape => &mut self.has_shape_expr,
ForeignHandler::Is => &mut self.is_expr,
ForeignHandler::Clone => &mut self.clone_expr,
ForeignHandler::ToString => &mut self.to_string_expr,
ForeignHandler::Equals => &mut self.equals_expr,
ForeignHandler::HashCode => &mut self.hash_code_expr,
ForeignHandler::PartialCompare => &mut self.partial_compare_expr,
ForeignHandler::Compare => &mut self.compare_expr,
}
}
pub fn handler_callee(&self, handler: ForeignHandler) -> Option<String> {
let expression = match handler {
ForeignHandler::Encode => self.encode_expr.as_deref(),
ForeignHandler::Decode => self.decode_expr.as_deref(),
ForeignHandler::Default => self.default_expr.as_deref(),
ForeignHandler::HasShape => self.has_shape_expr.as_deref(),
ForeignHandler::Is => self.is_expr.as_deref(),
ForeignHandler::Clone => self.clone_expr.as_deref(),
ForeignHandler::ToString => self.to_string_expr.as_deref(),
ForeignHandler::Equals => self.equals_expr.as_deref(),
ForeignHandler::HashCode => self.hash_code_expr.as_deref(),
ForeignHandler::PartialCompare => self.partial_compare_expr.as_deref(),
ForeignHandler::Compare => self.compare_expr.as_deref(),
}?;
if self.builtin {
return Some(format!("({expression})"));
}
let name = handler.export_name(&self.name);
crate::import_registry::with_registry_mut(|registry| {
registry.request_import(&name, None, FOREIGN_HANDLERS_MODULE, false);
});
Some(name)
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CfgFlags {
#[serde(default)]
pub features: Vec<String>,
#[serde(default)]
pub target: Option<String>,
#[serde(default)]
pub debug_assertions: bool,
#[serde(default)]
pub custom: HashMap<String, serde_json::Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DeprecatedConfig {
#[serde(default = "crate::config::default_true")]
pub runtime_warn: bool,
#[serde(default)]
pub fail_on_use: bool,
}
impl Default for DeprecatedConfig {
fn default() -> Self {
Self {
runtime_warn: true,
fail_on_use: false,
}
}
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum MustUseMode {
#[default]
Lint,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MustUseConfig {
#[serde(default)]
pub mode: MustUseMode,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BuildtimeConfig {
#[serde(default = "default_buildtime_timeout_ms")]
pub timeout_ms: u64,
#[serde(default = "default_buildtime_max_heap_mb")]
pub max_heap_mb: usize,
#[serde(default = "default_buildtime_fs_read")]
pub fs_read: Vec<String>,
#[serde(default)]
pub env_allow: Vec<String>,
#[serde(default)]
pub flags: BTreeMap<String, String>,
}
impl Default for BuildtimeConfig {
fn default() -> Self {
Self {
timeout_ms: default_buildtime_timeout_ms(),
max_heap_mb: default_buildtime_max_heap_mb(),
fs_read: default_buildtime_fs_read(),
env_allow: Vec::new(),
flags: BTreeMap::new(),
}
}
}
pub fn default_buildtime_timeout_ms() -> u64 {
5_000
}
pub fn default_buildtime_max_heap_mb() -> usize {
256
}
pub fn default_buildtime_fs_read() -> Vec<String> {
vec!["**".to_string()]
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NonExhaustiveConfig {
#[serde(default = "default_non_exhaustive_brand")]
pub brand: String,
}
impl Default for NonExhaustiveConfig {
fn default() -> Self {
Self {
brand: default_non_exhaustive_brand(),
}
}
}
fn default_non_exhaustive_brand() -> String {
"__nonExhaustive".to_string()
}
pub(crate) fn default_true() -> bool {
true
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MacroforgeConfig {
#[serde(default)]
pub keep_decorators: bool,
#[serde(default = "default_generate_convenience_const")]
pub generate_convenience_const: bool,
#[serde(default)]
pub foreign_types: Vec<ForeignTypeConfig>,
#[serde(default)]
pub cfg: CfgFlags,
#[serde(default)]
pub deprecated: DeprecatedConfig,
#[serde(default)]
pub must_use: MustUseConfig,
#[serde(default)]
pub non_exhaustive: NonExhaustiveConfig,
#[serde(default)]
pub buildtime: BuildtimeConfig,
}
pub fn default_generate_convenience_const() -> bool {
true
}
impl Default for MacroforgeConfig {
fn default() -> Self {
Self {
keep_decorators: false,
generate_convenience_const: true,
foreign_types: Vec::new(),
cfg: CfgFlags::default(),
deprecated: DeprecatedConfig::default(),
must_use: MustUseConfig::default(),
non_exhaustive: NonExhaustiveConfig::default(),
buildtime: BuildtimeConfig::default(),
}
}
}