#![allow(clippy::result_large_err)]
use std::collections::BTreeMap;
use std::fmt;
use std::sync::{Arc, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};
use indexmap::IndexMap;
use serde_json::json;
use tabnas::{
ActionError, Context, GrammarSetting, GrammarSpec, Plugin, PluginError, Rule, Tabnas,
TabnasError, Token, Value,
};
use tabnas_directive::{set_node, DirectiveOptions, RuleMod, RulesOption};
mod preload;
mod processor;
mod resolver;
mod vfs;
pub use preload::{preload_files, preload_files_with, PreloadOptions};
pub use processor::{default_processor, jsonic_processor, parse_nested, Processor, ProcessorInput};
pub use resolver::{FileResolver, MapResolver, PkgResolver};
pub use vfs::{os_fs, DirEntry, MapFs, OsFs, SharedFs, SourceFs};
pub const VERSION: &str = "0.6.0";
pub const NONE: &str = "";
pub const TOP: &str = "\0TOP";
pub const PLUGIN_NAME: &str = "MultiSource";
pub const RULE_NAME: &str = "multisource";
pub const DEFAULT_MARKCHAR: &str = "@";
pub const DEFAULT_MAX_DEPTH: usize = 64;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PathSpec {
pub kind: String,
pub path: Option<String>,
pub full: Option<String>,
pub base: String,
pub abs: bool,
}
#[derive(Clone, Debug)]
pub struct Resolution {
pub spec: PathSpec,
pub src: Option<String>,
pub val: Value,
pub found: bool,
pub search: Vec<String>,
pub err: Option<Box<TabnasError>>,
}
impl Default for Resolution {
fn default() -> Self {
Resolution::not_found(PathSpec::default())
}
}
impl Resolution {
pub fn not_found(spec: PathSpec) -> Self {
Resolution {
spec,
src: None,
val: Value::Undefined,
found: false,
search: Vec::new(),
err: None,
}
}
pub fn found(mut spec: PathSpec, full: impl Into<String>, src: impl Into<String>) -> Self {
let full = full.into();
spec.kind = ext_kind(Some(&full));
spec.full = Some(full);
Resolution {
spec,
src: Some(src.into()),
val: Value::Undefined,
found: true,
search: Vec::new(),
err: None,
}
}
pub fn with_search(mut self, search: Vec<String>) -> Self {
self.search = search;
self
}
pub fn full_path(&self) -> String {
self.spec
.full
.clone()
.or_else(|| self.spec.path.clone())
.unwrap_or_else(|| "no-path".to_string())
}
}
#[derive(Clone, Copy)]
pub struct ResolverInput<'a> {
pub options: &'a MultiSourceOptions,
pub meta: &'a Value,
}
impl fmt::Debug for ResolverInput<'_> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ResolverInput")
.field("meta", self.meta)
.finish_non_exhaustive()
}
}
impl ResolverInput<'_> {
pub fn source_path(&self) -> Option<String> {
meta_multisource_string(self.meta, "path")
}
}
pub trait Resolver: Send + Sync {
fn resolve(&self, reference: Option<&str>, input: &ResolverInput<'_>) -> Resolution;
}
impl<F> Resolver for F
where
F: Fn(Option<&str>, &ResolverInput<'_>) -> Resolution + Send + Sync,
{
fn resolve(&self, reference: Option<&str>, input: &ResolverInput<'_>) -> Resolution {
self(reference, input)
}
}
pub type SharedResolver = Arc<dyn Resolver>;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Dependency {
pub tar: String,
pub src: String,
pub wen: u64,
}
pub type DependencyMap = BTreeMap<String, BTreeMap<String, Dependency>>;
#[derive(Clone)]
pub enum ProcessorEntry {
Call(Arc<dyn Processor>),
Alias(String),
}
impl fmt::Debug for ProcessorEntry {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Call(_) => formatter.write_str("ProcessorEntry::Call(<function>)"),
Self::Alias(kind) => write!(formatter, "ProcessorEntry::Alias({kind:?})"),
}
}
}
#[derive(Clone)]
pub struct MultiSourceOptions {
pub resolver: SharedResolver,
pub path: String,
pub markchar: String,
pub processor: IndexMap<String, ProcessorEntry>,
pub implicit_ext: Vec<String>,
pub preload: Option<PreloadOptions>,
pub fs: Option<SharedFs>,
pub deps: Option<Arc<Mutex<DependencyMap>>>,
pub max_depth: usize,
}
impl fmt::Debug for MultiSourceOptions {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("MultiSourceOptions")
.field("path", &self.path)
.field("markchar", &self.markchar)
.field("processor", &self.processor)
.field("implicit_ext", &self.implicit_ext)
.field("preload", &self.preload)
.field("fs", &self.fs.as_ref().map(|_| "<SourceFs>"))
.field("deps", &self.deps.as_ref().map(|_| "<DependencyMap>"))
.field("max_depth", &self.max_depth)
.finish_non_exhaustive()
}
}
impl Default for MultiSourceOptions {
fn default() -> Self {
Self::new(MapResolver::new())
}
}
impl MultiSourceOptions {
pub fn new(resolver: impl Resolver + 'static) -> Self {
MultiSourceOptions {
resolver: Arc::new(resolver),
path: String::new(),
markchar: DEFAULT_MARKCHAR.to_string(),
processor: default_processors(),
implicit_ext: default_implicit_ext(),
preload: None,
fs: None,
deps: None,
max_depth: DEFAULT_MAX_DEPTH,
}
}
pub fn with_resolver(mut self, resolver: SharedResolver) -> Self {
self.resolver = resolver;
self
}
pub fn with_path(mut self, path: impl Into<String>) -> Self {
self.path = path.into();
self
}
pub fn with_markchar(mut self, markchar: impl Into<String>) -> Self {
self.markchar = markchar.into();
self
}
pub fn with_processor(
mut self,
kind: impl Into<String>,
processor: impl Processor + 'static,
) -> Self {
self.processor
.insert(kind.into(), ProcessorEntry::Call(Arc::new(processor)));
self
}
pub fn with_processor_alias(
mut self,
kind: impl Into<String>,
target: impl Into<String>,
) -> Self {
self.processor
.insert(kind.into(), ProcessorEntry::Alias(target.into()));
self
}
pub fn with_processors(mut self, processors: IndexMap<String, ProcessorEntry>) -> Self {
self.processor = processors;
self
}
pub fn with_implicit_ext<I, S>(mut self, extensions: I) -> Self
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
self.implicit_ext = extensions
.into_iter()
.map(|ext| dotted(ext.as_ref()))
.collect();
self
}
pub fn with_preload(mut self, preload: PreloadOptions) -> Self {
self.preload = Some(preload);
self
}
pub fn with_fs(mut self, filesystem: impl SourceFs + 'static) -> Self {
self.fs = Some(Arc::new(filesystem));
self
}
pub fn with_shared_fs(mut self, filesystem: SharedFs) -> Self {
self.fs = Some(filesystem);
self
}
pub fn with_deps(mut self, deps: Arc<Mutex<DependencyMap>>) -> Self {
self.deps = Some(deps);
self
}
pub fn with_max_depth(mut self, max_depth: usize) -> Self {
self.max_depth = max_depth;
self
}
pub fn processor_for(&self, kind: &str) -> Option<Arc<dyn Processor>> {
let fallback = match self.processor.get(NONE) {
Some(ProcessorEntry::Call(processor)) => Some(Arc::clone(processor)),
_ => None,
};
match self.processor.get(kind) {
Some(ProcessorEntry::Call(processor)) => Some(Arc::clone(processor)),
Some(ProcessorEntry::Alias(target)) => match self.processor.get(target.as_str()) {
Some(ProcessorEntry::Call(processor)) => Some(Arc::clone(processor)),
_ => fallback,
},
None => fallback,
}
}
}
pub fn default_processors() -> IndexMap<String, ProcessorEntry> {
let mut processors = IndexMap::new();
processors.insert(
NONE.to_string(),
ProcessorEntry::Call(Arc::new(default_processor)),
);
processors.insert(
"jsonic".to_string(),
ProcessorEntry::Call(Arc::new(jsonic_processor)),
);
processors.insert(
"jsc".to_string(),
ProcessorEntry::Alias("jsonic".to_string()),
);
processors
}
pub fn default_implicit_ext() -> Vec<String> {
vec![
".jsonic".to_string(),
".jsc".to_string(),
".json".to_string(),
]
}
fn dotted(ext: &str) -> String {
if ext.starts_with('.') {
ext.to_string()
} else {
format!(".{ext}")
}
}
pub fn ext_kind(full: Option<&str>) -> String {
let Some(full) = full else {
return NONE.to_string();
};
let segment = match full.rfind(['/', '\\']) {
Some(index) => &full[index + 1..],
None => full,
};
match segment.rfind('.') {
Some(index) => segment[index + 1..].to_string(),
None => NONE.to_string(),
}
}
pub fn resolve_path_spec(reference: Option<&str>, base: &str) -> PathSpec {
let path = reference.map(str::to_string);
let abs = path
.as_deref()
.map(|path| path.starts_with('/') || path.starts_with('\\'))
.unwrap_or(false);
let full = match path.as_deref() {
Some(path) if abs => Some(path.to_string()),
Some(path) if !path.is_empty() => Some(if base.is_empty() {
path.to_string()
} else {
format!("{base}/{path}")
}),
_ => None,
};
PathSpec {
kind: ext_kind(full.as_deref()),
path,
full,
base: base.to_string(),
abs,
}
}
pub fn build_potentials(full: &str, implicit_ext: &[String]) -> Vec<String> {
if full.is_empty() {
return Vec::new();
}
let mut potentials = vec![full.to_string()];
let segment = match full.rfind(['/', '\\']) {
Some(index) => &full[index + 1..],
None => full,
};
if segment.contains('.') {
return potentials;
}
for ext in implicit_ext {
potentials.push(format!("{full}{ext}"));
}
for ext in implicit_ext {
potentials.push(format!("{full}/index{ext}"));
}
if !segment.is_empty() && segment != "." {
for ext in implicit_ext {
potentials.push(format!("{full}/index.{segment}{ext}"));
}
}
potentials
}
pub fn source_dir(path: &str) -> String {
let trimmed = path.trim_end_matches(['/', '\\']);
match trimmed.rfind(['/', '\\']) {
None => String::new(),
Some(0) => trimmed[..1].to_string(),
Some(index) => trimmed[..index].to_string(),
}
}
fn meta_object(meta: &Value) -> Option<&IndexMap<String, Value>> {
match meta {
Value::Object(map) => Some(map),
Value::MapRef(map) => Some(&map.value),
_ => None,
}
}
fn meta_get<'a>(meta: &'a Value, key: &str) -> Option<&'a Value> {
meta_object(meta).and_then(|map| map.get(key))
}
fn meta_multisource_string(meta: &Value, key: &str) -> Option<String> {
match meta_get(meta, RULE_NAME).and_then(|entry| meta_get(entry, key)) {
Some(Value::String(text)) => Some(text.clone()),
Some(Value::Text(text)) => Some(text.string.clone()),
_ => None,
}
}
fn is_nested_meta(meta: &Value) -> bool {
matches!(
meta_get(meta, RULE_NAME).and_then(|entry| meta_get(entry, NESTED_MARK)),
Some(Value::Bool(true))
)
}
fn meta_parents(meta: &Value) -> Vec<String> {
match meta_get(meta, RULE_NAME).and_then(|entry| meta_get(entry, "parents")) {
Some(Value::Array(items)) => items
.iter()
.filter_map(|item| match item {
Value::String(text) => Some(text.clone()),
Value::Text(text) => Some(text.string.clone()),
_ => None,
})
.collect(),
_ => Vec::new(),
}
}
const NESTED_MARK: &str = "nested";
fn child_meta(
parent: &Value,
resolution: &Resolution,
parents: &[String],
dive: Option<&Value>,
ticket: &str,
) -> Value {
let mut child = meta_object(parent).cloned().unwrap_or_default();
let previous = meta_get(parent, RULE_NAME)
.and_then(meta_object)
.cloned()
.unwrap_or_default();
let mut entry = previous;
entry.insert(
"parents".to_string(),
Value::array(parents.iter().cloned().map(Value::String).collect()),
);
entry.insert(
"path".to_string(),
match &resolution.spec.full {
Some(full) => Value::String(full.clone()),
None => Value::Undefined,
},
);
entry.insert(NESTED_MARK.to_string(), Value::Bool(true));
entry.insert(REPORT_TICKET.to_string(), Value::String(ticket.to_string()));
child.insert(RULE_NAME.to_string(), Value::object(entry));
if let Some(path) = &resolution.spec.path {
child.insert("fileName".to_string(), Value::String(path.clone()));
}
if let Some(Value::Array(segments)) = dive {
let mut path = IndexMap::new();
path.insert("base".to_string(), Value::array(segments.as_ref().clone()));
child.insert("path".to_string(), Value::object(path));
}
Value::object(child)
}
#[derive(Default)]
struct NestedParser {
current: Mutex<Option<Arc<Tabnas>>>,
}
impl NestedParser {
fn publish(&self, parser: &Tabnas) {
if let Ok(mut slot) = self.current.lock() {
*slot = Some(Arc::new(parser.clone()));
}
}
fn get(&self) -> Option<Arc<Tabnas>> {
self.current.lock().ok().and_then(|slot| slot.clone())
}
}
type Report = (String, Vec<(String, Value)>);
#[derive(Default)]
struct LastReport {
slots: Mutex<BTreeMap<String, Report>>,
next: std::sync::atomic::AtomicU64,
}
impl LastReport {
fn ticket(&self) -> String {
let count = self.next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
format!("{count}")
}
fn record(&self, ticket: &str, code: &str, details: &[(String, Value)]) {
if let Ok(mut slots) = self.slots.lock() {
slots.insert(ticket.to_string(), (code.to_string(), details.to_vec()));
}
}
fn take(&self, ticket: &str, code: &str) -> Option<Vec<(String, Value)>> {
let mut slots = self.slots.lock().ok()?;
match slots.remove(ticket) {
Some((recorded, details)) if recorded == code => Some(details),
_ => None,
}
}
fn discard(&self, ticket: &str) {
if let Ok(mut slots) = self.slots.lock() {
slots.remove(ticket);
}
}
}
const REPORT_TICKET: &str = "report";
pub fn plugin_with(options: MultiSourceOptions) -> Plugin {
let options = Arc::new(normalize(options));
Plugin::new(PLUGIN_NAME, move |parser, _plugin_options| {
install(parser, Arc::clone(&options)).map_err(PluginError::from)
})
}
pub fn plugin() -> Plugin {
plugin_with(MultiSourceOptions::default())
}
pub fn multisource(
parser: &mut Tabnas,
options: MultiSourceOptions,
) -> Result<(), MultiSourceError> {
parser
.use_plugin(plugin_with(options), None)
.map(|_| ())
.map_err(MultiSourceError::from)
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MultiSourceError(pub String);
impl fmt::Display for MultiSourceError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.0)
}
}
impl std::error::Error for MultiSourceError {}
impl From<PluginError> for MultiSourceError {
fn from(error: PluginError) -> Self {
Self(error.0)
}
}
impl From<MultiSourceError> for PluginError {
fn from(error: MultiSourceError) -> Self {
Self(error.0)
}
}
fn normalize(mut options: MultiSourceOptions) -> MultiSourceOptions {
if options.markchar.is_empty() {
options.markchar = DEFAULT_MARKCHAR.to_string();
}
for ext in &mut options.implicit_ext {
if !ext.starts_with('.') {
*ext = format!(".{ext}");
}
}
if options.max_depth == 0 {
options.max_depth = DEFAULT_MAX_DEPTH;
}
options
}
fn install(parser: &mut Tabnas, options: Arc<MultiSourceOptions>) -> Result<(), MultiSourceError> {
let rules = parser.rule_names();
for required in ["val", "map", "pair"] {
if !rules.iter().any(|name| name == required) {
return Err(MultiSourceError(format!(
"MultiSource needs a host grammar supplying the {required:?} rule: \
install one that defines val, map and pair (tabnas-jsonic, for \
example) before this plugin"
)));
}
}
let nested = Arc::new(NestedParser::default());
let reports = Arc::new(LastReport::default());
parser
.set_options(|engine| {
engine.error.insert(
"multisource_not_found".to_string(),
"source not found: {path}".to_string(),
);
engine.error.insert(
"multisource_cycle".to_string(),
"source includes itself: {path}".to_string(),
);
engine.error.insert(
"multisource_depth".to_string(),
"source nesting is too deep: {path}".to_string(),
);
engine.hint.insert(
"multisource_not_found".to_string(),
"The source path {path} was not found.\n\nSearch paths:\n{searchstr}".to_string(),
);
engine.hint.insert(
"multisource_cycle".to_string(),
"Including {path} here would loop forever:\n\n{loop}\n\n\
A source may be included from more than one place, but it cannot \
be an ancestor of itself."
.to_string(),
);
engine.hint.insert(
"multisource_depth".to_string(),
"Loading {path} would nest sources more than {max} deep.\n\n\
Each source is loaded inside the parse that referenced it, so an \
unbounded chain would exhaust the stack. Raise max_depth if the \
chain is genuine."
.to_string(),
);
})
.map_err(|error| MultiSourceError(error.to_string()))?;
{
let options = Arc::clone(&options);
let nested = Arc::clone(&nested);
parser.parse_prepare_with_instance(move |instance, context, _meta| {
if !context.source.contains(options.markchar.as_str()) {
return;
}
if is_nested_meta(&context.meta) {
return;
}
nested.publish(instance);
});
}
let name = RULE_NAME.to_string();
let markchar = options.markchar.clone();
let action_options = Arc::clone(&options);
let action_nested = Arc::clone(&nested);
let action_reports = Arc::clone(&reports);
let directive = DirectiveOptions::new(name.clone(), markchar)
.with_rules(
RulesOption::new()
.open_rule("val", RuleMod::new())
.open_rule("pair", RuleMod::when(|rule, _context| rule.lte("pk", 0))),
)
.with_token_action(move |rule, context| {
directive_action(
&action_options,
&action_nested,
&action_reports,
rule,
context,
)
})
.with_custom(move |parser, config| {
if let Err(error) = install_grammar(parser, &config.name) {
panic!("MultiSource grammar: {error}");
}
});
tabnas_directive::apply(parser, directive).map_err(|error| MultiSourceError(error.to_string()))
}
fn install_grammar(parser: &mut Tabnas, name: &str) -> Result<(), MultiSourceError> {
let open_token = format!("#OD_{name}");
let top_counter = format!("{name}_top");
parser.alt_condition("@ms-pk-val", |rule, _context| {
rule.gt("pk", 0)
&& rule
.parent_rule
.as_ref()
.map(|parent| parent.name.as_ref() != "pair")
.unwrap_or(true)
});
parser.alt_condition("@ms-pk", |rule, _context| rule.gt("pk", 0));
parser.alt_condition("@ms-top", |rule, _context| rule.d == 0);
let counter = top_counter.clone();
parser.alt_condition("@ms-top-map", move |rule, _context| {
rule.d == 1 && rule.eq(&counter, 1)
});
let document = json!({
"rule": {
"val": {
"open": [
{ "s": open_token, "c": "@ms-pk-val", "b": 1 },
{
"s": open_token,
"c": "@ms-top",
"p": "map",
"b": 1,
"n": { top_counter.clone(): 1 },
},
],
},
"map": {
"open": [{
"s": open_token,
"c": "@ms-top-map",
"p": "pair",
"b": 1,
"a": "@object$",
"k": { "object$": { "implicit": true } },
}],
"close": [{ "s": open_token, "c": "@ms-pk", "b": 1 }],
},
"pair": {
"close": [{ "s": open_token, "c": "@ms-pk", "b": 1 }],
},
},
});
let spec =
GrammarSpec::from_value(document).map_err(|error| MultiSourceError(error.to_string()))?;
parser
.grammar_with_setting(&spec, &GrammarSetting::groups(name))
.map(|_| ())
.map_err(|error| MultiSourceError(error.to_string()))
}
fn reference_of(value: &Value) -> Option<String> {
match value {
Value::Object(_) | Value::MapRef(_) => coerce_reference(meta_get(value, "path").as_ref()?),
other => coerce_reference(other),
}
}
fn coerce_reference(value: &Value) -> Option<String> {
match value {
Value::String(text) => Some(text.clone()),
Value::Text(text) => Some(text.string.clone()),
Value::Number(number) => Some(format_number(*number)),
Value::Bool(flag) => Some(flag.to_string()),
_ => None,
}
}
fn format_number(number: f64) -> String {
if number.is_nan() {
return "NaN".to_string();
}
if number == 0.0 {
return "0".to_string();
}
if number < 0.0 {
return format!("-{}", format_number(-number));
}
if number.is_infinite() {
return "Infinity".to_string();
}
let shortest = format!("{number:e}");
let shortest_k = shortest
.split_once('e')
.map(|(mantissa, _)| mantissa.chars().filter(char::is_ascii_digit).count())
.expect("a finite f64 always formats with an exponent");
let exponential = format!("{:.*e}", shortest_k - 1, number);
let (mantissa, exponent) = exponential
.split_once('e')
.expect("a finite f64 always formats with an exponent");
let digits = mantissa
.chars()
.filter(|digit| *digit != '.')
.collect::<String>();
let digits = digits.trim_end_matches('0');
let digits = if digits.is_empty() { "0" } else { digits };
let k = digits.len() as i32;
let n = exponent
.parse::<i32>()
.expect("a formatted exponent is an integer")
+ 1;
if (k..=21).contains(&n) {
let mut text = digits.to_string();
text.push_str(&"0".repeat((n - k) as usize));
text
} else if (1..=21).contains(&n) {
let point = n as usize;
format!("{}.{}", &digits[..point], &digits[point..])
} else if (-5..=0).contains(&n) {
format!("0.{}{}", "0".repeat(-n as usize), digits)
} else {
let sign = if n - 1 < 0 { '-' } else { '+' };
let power = (n - 1).abs();
if k == 1 {
format!("{digits}e{sign}{power}")
} else {
format!("{}.{}e{sign}{power}", &digits[..1], &digits[1..])
}
}
}
fn error_token(rule: &Rule, context: &Context) -> Option<Token> {
rule.parent_rule
.as_ref()
.and_then(|parent| parent.o.first())
.or_else(|| rule.o.first())
.cloned()
.or_else(|| context.t0().cloned())
}
fn fail(
reports: &LastReport,
rule: &Rule,
context: &Context,
code: &str,
details: Vec<(String, Value)>,
) -> Result<Option<Token>, ActionError> {
if let Some(ticket) = meta_multisource_string(&context.meta, REPORT_TICKET) {
reports.record(&ticket, code, &details);
}
match error_token(rule, context) {
Some(mut token) => {
token.bad_with_details(code, details);
Ok(Some(token))
}
None => Err(ActionError::new(code, format!("[{code}]"))),
}
}
fn directive_action(
options: &Arc<MultiSourceOptions>,
nested: &Arc<NestedParser>,
reports: &Arc<LastReport>,
rule: &mut Rule,
context: &mut Context,
) -> Result<Option<Token>, ActionError> {
let from = rule
.parent_rule
.as_ref()
.map(|parent| parent.name.to_string())
.unwrap_or_default();
let reference = reference_of(&rule.child_node);
let mut resolution = {
let input = ResolverInput {
options,
meta: &context.meta,
};
options.resolver.resolve(reference.as_deref(), &input)
};
if !resolution.found {
let mut search = resolution.search.clone();
if search.is_empty() {
if let Some(full) = &resolution.spec.full {
search.push(full.clone());
}
}
let named = resolution
.spec
.path
.clone()
.or_else(|| reference.clone())
.unwrap_or_default();
return fail(
reports,
rule,
context,
"multisource_not_found",
vec![
("path".to_string(), Value::String(named)),
(
"full".to_string(),
Value::String(resolution.spec.full.clone().unwrap_or_default()),
),
("searchstr".to_string(), Value::String(search.join("\n"))),
],
);
}
let fullpath = resolution.full_path();
if resolution.spec.kind.is_empty() {
resolution.spec.kind = NONE.to_string();
}
let mut parents = meta_parents(&context.meta);
if let Some(path) = meta_multisource_string(&context.meta, "path") {
parents.push(path);
}
if let Some(index) = parents.iter().position(|parent| parent == &fullpath) {
let mut loop_path: Vec<String> = parents[index..].to_vec();
loop_path.push(fullpath.clone());
return fail(
reports,
rule,
context,
"multisource_cycle",
vec![
("path".to_string(), Value::String(fullpath)),
("loop".to_string(), Value::String(loop_path.join(" -> "))),
],
);
}
if parents.len() >= options.max_depth {
return fail(
reports,
rule,
context,
"multisource_depth",
vec![
("path".to_string(), Value::String(fullpath)),
("max".to_string(), Value::Number(options.max_depth as f64)),
],
);
}
if let Some(deps) = &options.deps {
let target = parents.last().cloned().unwrap_or_else(|| TOP.to_string());
if let Ok(mut deps) = deps.lock() {
deps.entry(target.clone()).or_default().insert(
fullpath.clone(),
Dependency {
tar: target,
src: fullpath.clone(),
wen: now_millis(),
},
);
}
}
let dive = rule.k.get("path").cloned();
let ticket = reports.ticket();
let meta = child_meta(&context.meta, &resolution, &parents, dive.as_ref(), &ticket);
let Some(parser) = nested.get() else {
return Err(ActionError::new(
"internal",
"MultiSource: no parser was published for the nested parse",
));
};
if let Some(processor) = options.processor_for(&resolution.spec.kind) {
let input = ProcessorInput {
options,
meta: &meta,
parser: &parser,
depth: parents.len(),
};
processor.process(&mut resolution, &input);
}
if let Some(error) = resolution.err.take() {
let code = if error.code.is_empty() {
"unexpected".to_string()
} else {
error.code.clone()
};
let details = reports.take(&ticket, &code).unwrap_or_else(|| {
vec![
("path".to_string(), Value::String(fullpath)),
("searchstr".to_string(), Value::String(error.detail.clone())),
]
});
return fail(reports, rule, context, &code, details);
}
reports.discard(&ticket);
let value = std::mem::replace(&mut resolution.val, Value::Undefined);
if from == "pair" {
splice_into_parent(rule, context, value);
} else {
set_node(rule, value);
}
Ok(None)
}
fn now_millis() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|since| since.as_millis() as u64)
.unwrap_or(0)
}
fn splice_into_parent(rule: &mut Rule, context: &mut Context, value: Value) {
let Some(target) = rule
.parent_rule
.as_ref()
.and_then(|parent| parent.parent_rule.as_ref())
.map(|grandparent| grandparent.node.clone())
else {
return;
};
let merge = context.options.map.merge.clone();
let extend = context.options.map.extend;
if let Some(merge) = merge {
let base = target.borrow().clone();
let merged = merge(base, value, rule, context);
*target.borrow_mut() = merged;
return;
}
if extend {
let base = target.borrow().clone();
let merged = deep_merge(base, value);
*target.borrow_mut() = merged;
return;
}
let Some(entries) = object_entries(&value) else {
return;
};
let mut node = target.borrow_mut();
match &mut *node {
Value::Object(map) => {
let map = Arc::make_mut(map);
for (key, item) in entries {
map.insert(key, item);
}
}
Value::MapRef(map) => {
let map = Arc::make_mut(map);
for (key, item) in entries {
map.value.insert(key, item);
}
}
_ => {}
}
}
fn object_entries(value: &Value) -> Option<Vec<(String, Value)>> {
match value {
Value::Object(map) => Some(
map.iter()
.map(|(key, item)| (key.clone(), item.clone()))
.collect(),
),
Value::MapRef(map) => Some(
map.value
.iter()
.map(|(key, item)| (key.clone(), item.clone()))
.collect(),
),
_ => None,
}
}
fn deep_merge(base: Value, overlay: Value) -> Value {
const DANGEROUS: [&str; 3] = ["__proto__", "constructor", "prototype"];
fn merge_entries(base: &mut IndexMap<String, Value>, overlay: IndexMap<String, Value>) {
for (key, value) in overlay {
if DANGEROUS.contains(&key.as_str()) {
continue;
}
let previous = base.get(&key).cloned().unwrap_or(Value::Undefined);
base.insert(key, deep_merge(previous, value));
}
}
fn merge_items(base: &mut Vec<Value>, overlay: Vec<Value>) {
for (index, value) in overlay.into_iter().enumerate() {
if index < base.len() {
let previous = std::mem::replace(&mut base[index], Value::Undefined);
base[index] = deep_merge(previous, value);
} else {
base.push(value);
}
}
}
match (base, overlay) {
(base, Value::Undefined) => base,
(Value::Object(base), Value::Object(overlay)) => {
let mut base = unwrap_arc(base);
merge_entries(&mut base, unwrap_arc(overlay));
Value::object(base)
}
(Value::Object(base), Value::MapRef(overlay)) => {
let mut base = unwrap_arc(base);
merge_entries(&mut base, unwrap_arc(overlay).value);
Value::object(base)
}
(Value::MapRef(base), Value::Object(overlay)) => {
let mut base = unwrap_arc(base);
merge_entries(&mut base.value, unwrap_arc(overlay));
Value::MapRef(Arc::new(base))
}
(Value::MapRef(base), Value::MapRef(overlay)) => {
let mut base = unwrap_arc(base);
merge_entries(&mut base.value, unwrap_arc(overlay).value);
Value::MapRef(Arc::new(base))
}
(Value::Array(base), Value::Array(overlay)) => {
let mut base = unwrap_arc(base);
merge_items(&mut base, unwrap_arc(overlay));
Value::array(base)
}
(Value::Array(base), Value::ListRef(overlay)) => {
let mut base = unwrap_arc(base);
merge_items(&mut base, unwrap_arc(overlay).value);
Value::array(base)
}
(Value::ListRef(base), Value::Array(overlay)) => {
let mut base = unwrap_arc(base);
merge_items(&mut base.value, unwrap_arc(overlay));
Value::ListRef(Arc::new(base))
}
(Value::ListRef(base), Value::ListRef(overlay)) => {
let mut base = unwrap_arc(base);
merge_items(&mut base.value, unwrap_arc(overlay).value);
Value::ListRef(Arc::new(base))
}
(_, overlay) => overlay,
}
}
fn unwrap_arc<T: Clone>(shared: Arc<T>) -> T {
Arc::try_unwrap(shared).unwrap_or_else(|shared| (*shared).clone())
}
#[cfg(test)]
mod tests {
use super::*;
fn object(entries: &[(&str, Value)]) -> Value {
Value::object(
entries
.iter()
.map(|(key, value)| (key.to_string(), value.clone()))
.collect(),
)
}
fn number(value: f64) -> Value {
Value::Number(value)
}
#[test]
fn deep_merge_agrees_with_the_jsonic_merge_it_replaces() {
let cases: Vec<(Value, Value)> = vec![
(
object(&[("a", number(1.0)), ("n", object(&[("x", number(1.0))]))]),
object(&[("b", number(2.0)), ("n", object(&[("y", number(2.0))]))]),
),
(
Value::array(vec![number(1.0), object(&[("a", number(1.0))])]),
Value::array(vec![
number(9.0),
object(&[("b", number(2.0))]),
number(3.0),
]),
),
(
object(&[("a", number(1.0))]),
Value::array(vec![number(1.0)]),
),
(object(&[("a", number(1.0))]), Value::Undefined),
(Value::Null, object(&[("a", number(1.0))])),
(number(1.0), Value::String("s".to_string())),
(
object(&[("a", number(1.0))]),
object(&[
("__proto__", object(&[("polluted", Value::Bool(true))])),
("constructor", number(1.0)),
("prototype", number(2.0)),
("ok", number(3.0)),
]),
),
];
for (base, overlay) in cases {
let ours = deep_merge(base.clone(), overlay.clone());
let theirs = tabnas_jsonic::deep_merge(base.clone(), overlay.clone());
assert_eq!(ours, theirs, "deep_merge({base}, {overlay})");
}
}
#[test]
fn deep_merge_keeps_the_base_container_and_its_metadata() {
let mut meta = IndexMap::new();
meta.insert("tag".to_string(), Value::String("kept".to_string()));
let mut entries = IndexMap::new();
entries.insert("a".to_string(), number(1.0));
let base = Value::MapRef(Arc::new(tabnas::MapRef {
value: entries,
implicit: true,
meta,
}));
match deep_merge(base, object(&[("b", number(2.0))])) {
Value::MapRef(map) => {
assert!(map.implicit);
assert_eq!(map.meta.get("tag"), Some(&Value::String("kept".into())));
assert_eq!(map.value.get("a"), Some(&number(1.0)));
assert_eq!(map.value.get("b"), Some(&number(2.0)));
}
other => panic!("the base container kind is kept, got {other:?}"),
}
}
}
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
mod readme_examples {}