use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use serde_json::{Map, Value};
use crate::core::registry::{PackageFactory, WorkflowDef};
use crate::core::settings::{EntryDecl, Mark, PackageSettings, SettingsDecl, texts_at};
use crate::lang::FlmParsing;
use crate::model::names::Name;
use crate::model::options::{Bind, OptionValues};
pub trait CascadeOrigin: Clone + fmt::Display + fmt::Debug + PartialEq {
fn rank(&self) -> u32;
fn peer(&self) -> Option<&str>;
fn workflow(&self) -> Option<&str>;
fn higher_source(&self) -> Option<&str>;
fn resolve_path(&self, path: &str) -> Result<Option<String>, String>;
}
pub type Reach = BTreeMap<Name, BTreeSet<Name>>;
#[derive(Debug, Clone, PartialEq)]
pub struct SettingValue<O> {
pub value: Value,
pub origin: O,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Problem<O> {
pub origin: Option<O>,
pub detail: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Warning<O> {
pub kind: WarningKind,
pub problem: Problem<O>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum WarningKind {
UnknownFeature,
UndeclaredKey,
}
impl<O> fmt::Display for Problem<O> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.detail)
}
}
impl<O: fmt::Debug> std::error::Error for Problem<O> {}
fn wins_over<O: CascadeOrigin>(reach: &Reach, winner: &O, other: &O) -> bool {
let (Some(winner), Some(other)) = (winner.peer(), other.peer()) else { return false };
let reaches = |from: &str, to: &str| reach.get(from).is_some_and(|reached| reached.contains(to));
winner != other && reaches(winner, other) && !reaches(other, winner)
}
#[derive(Debug, Clone)]
struct Written<T, O> {
value: T,
origin: O,
disagreeing: Vec<(T, O)>,
}
fn decide_at<T: PartialEq, O: CascadeOrigin>(writes: &[(&T, &O)], reach: &Reach) -> Option<(usize, Vec<usize>)> {
let top = writes.iter().map(|(_, origin)| origin.rank()).max()?;
let at_top: Vec<usize> = (0..writes.len()).filter(|at| writes[*at].1.rank() == top).collect();
if !at_top.iter().any(|at| writes[*at].1.peer().is_some()) {
return Some((*at_top.last()?, Vec::new()));
}
let mut counting =
at_top.iter().copied().filter(|at| !at_top.iter().any(|other| wins_over(reach, writes[*other].1, writes[*at].1)));
let first = counting.next()?;
let disagreeing = counting.filter(|at| writes[*at].0 != writes[first].0).collect();
Some((first, disagreeing))
}
impl<T: PartialEq + Clone, O: CascadeOrigin> Written<T, O> {
fn decide<'w>(writes: impl IntoIterator<Item = (&'w T, &'w O)>, reach: &Reach) -> Option<Written<T, O>>
where
T: 'w,
O: 'w,
{
let writes: Vec<(&T, &O)> = writes.into_iter().collect();
let (first, disagreeing) = decide_at(&writes, reach)?;
let (value, origin) = writes[first];
let disagreeing = disagreeing.into_iter().map(|at| (writes[at].0.clone(), writes[at].1.clone())).collect();
Some(Written { value: value.clone(), origin: origin.clone(), disagreeing })
}
fn disagreement(&self, what: &str, show: impl Fn(&T) -> String, higher_writes: bool) -> Option<Problem<O>> {
if self.disagreeing.is_empty() {
return None;
}
let others: Vec<String> =
self.disagreeing.iter().map(|(value, origin)| format!("{} at {origin}", show(value))).collect();
let settle = match self.origin.higher_source() {
Some(higher) if higher_writes => format!(
"; make the values agree, make one of these packages use the other, or set the value in {higher}"
),
_ => String::from("; make the values agree, or make one of these packages use the other"),
};
Some(Problem {
origin: Some(self.origin.clone()),
detail: format!(
"the packages that set {what} must agree on its value when none of them uses another, directly \
or through other packages (the value of a package replaces those of the packages it uses), but {} \
is set at {} and {}{settle}",
show(&self.value),
self.origin,
others.join(" and ")
),
})
}
}
#[derive(Debug, Clone)]
struct FeatureValues<O> {
keys: BTreeMap<String, Vec<SettingValue<O>>>,
off: Vec<(bool, O)>,
written: Vec<O>,
}
impl<O> Default for FeatureValues<O> {
fn default() -> FeatureValues<O> {
FeatureValues { keys: BTreeMap::new(), off: Vec::new(), written: Vec::new() }
}
}
fn same_source<O: CascadeOrigin>(a: &O, b: &O) -> bool {
a.rank() == b.rank() && a.peer() == b.peer() && a.workflow() == b.workflow()
}
#[derive(Debug, Clone)]
pub struct Cascade<O: CascadeOrigin> {
features: BTreeMap<String, FeatureValues<O>>,
parsing: BTreeMap<String, Vec<(Value, O)>>,
workflow_fields: BTreeMap<String, BTreeMap<String, Vec<(Value, O)>>>,
reach: Reach,
}
impl<O: CascadeOrigin> Default for Cascade<O> {
fn default() -> Cascade<O> {
Cascade {
features: BTreeMap::new(),
parsing: BTreeMap::new(),
workflow_fields: BTreeMap::new(),
reach: Reach::new(),
}
}
}
#[derive(Debug, Clone)]
pub struct ReadSettings<O> {
pub packages: BTreeMap<Name, PackageSettings>,
pub document: OptionValues,
pub render: OptionValues,
pub warnings: Vec<Warning<O>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReadFailure<O> {
pub errors: Vec<Problem<O>>,
pub warnings: Vec<Warning<O>>,
}
impl<O> Default for ReadSettings<O> {
fn default() -> ReadSettings<O> {
ReadSettings {
packages: BTreeMap::new(),
document: OptionValues::default(),
render: OptionValues::default(),
warnings: Vec::new(),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct FeatureInEffect<O> {
pub switched_off: Option<O>,
pub keys: BTreeMap<String, KeyInEffect<O>>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct KeyInEffect<O> {
pub value: Value,
pub origin: O,
pub entry_origins: BTreeMap<String, O>,
pub below: BTreeMap<String, EntryOrigins<O>>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct EntryOrigins<O> {
pub entry_origins: BTreeMap<String, O>,
pub below: BTreeMap<String, EntryOrigins<O>>,
}
impl<O> Default for EntryOrigins<O> {
fn default() -> EntryOrigins<O> {
EntryOrigins { entry_origins: BTreeMap::new(), below: BTreeMap::new() }
}
}
impl<O> EntryOrigins<O> {
fn is_empty(&self) -> bool {
self.entry_origins.is_empty() && self.below.is_empty()
}
}
impl<O> KeyInEffect<O> {
pub fn origin_at(&self, path: &[&str]) -> &O {
let mut origin = &self.origin;
let (mut origins, mut below) = (&self.entry_origins, &self.below);
for name in path {
match origins.get(*name) {
Some(at) => origin = at,
None => break,
}
match below.get(*name) {
Some(level) => (origins, below) = (&level.entry_origins, &level.below),
None => break,
}
}
origin
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct WriteAt<O> {
pub value: Value,
pub origin: O,
pub in_effect: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub struct DecidedAt<O> {
pub depth: usize,
pub origin: Option<O>,
}
fn whole<O: CascadeOrigin>(writes: &[SettingValue<O>], reach: &Reach) -> Option<Written<Value, O>> {
Written::decide(writes.iter().map(|write| (&write.value, &write.origin)), reach)
}
pub(super) fn names(pattern: &str, path: &[String]) -> bool {
let segments: Vec<&str> = pattern.split('.').collect();
segments.len() == path.len() && segments.iter().zip(path).all(|(segment, name)| *segment == "*" || segment == name)
}
type Writes<'w, O> = Vec<(&'w Value, &'w O)>;
struct Combined<O> {
value: Value,
origin: O,
below: EntryOrigins<O>,
}
struct Combiner<'c> {
feature: &'c str,
decl: &'c SettingsDecl,
reach: &'c Reach,
}
struct Found<O> {
problems: Vec<Problem<O>>,
warnings: Vec<Warning<O>>,
}
impl<O> Default for Found<O> {
fn default() -> Found<O> {
Found { problems: Vec::new(), warnings: Vec::new() }
}
}
impl Combiner<'_> {
fn dotted(&self, path: &[String]) -> String {
format!("{}.{}", self.feature, path.join("."))
}
fn combine<O: CascadeOrigin>(
&self,
path: &mut Vec<String>,
writes: Writes<'_, O>,
default: Option<&Value>,
found: &mut Found<O>,
) -> Option<Combined<O>> {
let entry = self.decl.entry_in_force(&path.join("."));
if !self.decl.is_marked(path, Mark::MergeObjectKeyValues) {
let written = Written::decide(writes, self.reach)?;
let what = match path.split_last() {
Some((name, parent)) if !parent.is_empty() => {
format!("the entry `{name}` of `{}`", self.dotted(parent))
}
_ => format!("`{}`", self.dotted(path)),
};
found.problems.extend(written.disagreement(&what, shown, true));
let mut value = written.value;
if let (Some(entry), Value::Object(map)) = (entry, &mut value) {
map.retain(|name, _| {
let declared = entry.keys().contains(name);
if !declared {
found.warnings.push(self.undeclared(path, name, &written.origin));
}
declared
});
}
self.leave_out(path, &mut value);
return Some(Combined { value, origin: written.origin, below: EntryOrigins::default() });
}
let mut sorted = writes;
sorted.sort_by_key(|(_, origin)| origin.rank());
let origin = sorted.last()?.1.clone();
let defaults = match default {
Some(Value::Object(entries)) => Some(entries),
_ => self
.decl
.marks()
.iter()
.filter(|marks| marks.has(Mark::MergeObjectKeyValues) && names(&marks.path, path))
.find_map(|marks| self.decl.default_entries(&marks.path)),
};
let mut entries: Vec<(String, Option<&Value>, Writes<'_, O>)> = defaults
.into_iter()
.flatten()
.map(|(name, value)| (name.clone(), Some(value), Vec::new()))
.collect();
for (value, origin) in &sorted {
let Value::Object(map) = value else {
found.problems.push(Problem {
origin: Some((*origin).clone()),
detail: format!(
"the value of `{}` must be a map from each entry's name to the entry",
self.dotted(path)
),
});
continue;
};
for (name, value) in map {
if entry.is_some_and(|entry| !entry.keys().contains(name)) {
found.warnings.push(self.undeclared(path, name, origin));
continue;
}
let at = match entries.iter().position(|(entry, _, _)| entry == name) {
Some(at) => at,
None => {
entries.push((name.clone(), None, Vec::new()));
entries.len() - 1
}
};
entries[at].2.push((value, *origin));
}
}
let remove_false = self.decl.is_marked(path, Mark::RemoveKeyWhenValueIsFalse);
let mut value = Map::new();
let mut below = EntryOrigins::default();
for (name, default, writes) in entries {
path.push(name.clone());
let in_force = match self.combine(path, writes, default, found) {
Some(combined) => {
below.entry_origins.insert(name.clone(), combined.origin);
if !combined.below.is_empty() {
below.below.insert(name.clone(), combined.below);
}
combined.value
}
None => {
let mut value = default.cloned().unwrap_or(Value::Null);
self.leave_out(path, &mut value);
value
}
};
let to_default = in_force.is_null() && self.decl.is_marked(path, Mark::SetToDefaultWithNull);
path.pop();
if !to_default && !(remove_false && in_force == Value::Bool(false)) {
value.insert(name, in_force);
}
}
Some(Combined { value: Value::Object(value), origin, below })
}
fn undeclared<O: CascadeOrigin>(&self, path: &[String], name: &str, origin: &O) -> Warning<O> {
let detail = format!("Unknown setting ‘{name}’ in ‘{}’", self.dotted(path));
Warning { kind: WarningKind::UndeclaredKey, problem: Problem { origin: Some(origin.clone()), detail } }
}
fn leave_out(&self, path: &mut Vec<String>, value: &mut Value) {
match value {
Value::Object(map) => {
let remove_false = self.decl.is_marked(path, Mark::RemoveKeyWhenValueIsFalse);
map.retain(|name, item| {
path.push(name.clone());
self.leave_out(path, item);
let to_default = item.is_null() && self.decl.is_marked(path, Mark::SetToDefaultWithNull);
path.pop();
!to_default && !(remove_false && *item == Value::Bool(false))
});
}
Value::Array(items) => {
for (at, item) in items.iter_mut().enumerate() {
path.push(at.to_string());
self.leave_out(path, item);
path.pop();
}
}
_ => {}
}
}
}
fn resolve_paths<O: CascadeOrigin>(
decl: &SettingsDecl,
key: &str,
combined: &mut KeyInEffect<O>,
problems: &mut Vec<Problem<O>>,
) {
for mark in decl.marks().iter().filter(|mark| mark.has(Mark::Path)) {
let mut segments = mark.path.split('.');
if segments.next() != Some(key) {
continue;
}
let below: Vec<&str> = segments.collect();
let mut path = vec![key.to_string()];
let origins = (&combined.entry_origins, &combined.below);
resolve_in(decl, &mut path, &mut combined.value, &below, &combined.origin, origins, problems);
}
}
fn resolve_in<O: CascadeOrigin>(
decl: &SettingsDecl,
path: &mut Vec<String>,
value: &mut Value,
segments: &[&str],
origin: &O,
origins: (&BTreeMap<String, O>, &BTreeMap<String, EntryOrigins<O>>),
problems: &mut Vec<Problem<O>>,
) {
if !decl.is_marked(path, Mark::MergeObjectKeyValues) {
resolve_at(value, segments, origin, problems);
return;
}
let Value::Object(map) = value else { return };
let none = EntryOrigins::default();
for (name, entry) in map.iter_mut() {
let Some(entry_origin) = origins.0.get(name) else { continue };
let rest = match segments.split_first() {
None => segments,
Some((first, rest)) if *first == "*" || first == name => rest,
Some(_) => continue,
};
let below = origins.1.get(name).unwrap_or(&none);
path.push(name.clone());
resolve_in(decl, path, entry, rest, entry_origin, (&below.entry_origins, &below.below), problems);
path.pop();
}
}
fn resolve_at<O: CascadeOrigin>(value: &mut Value, segments: &[&str], origin: &O, problems: &mut Vec<Problem<O>>) {
texts_at(value, segments, &mut |text| match origin.resolve_path(text) {
Ok(Some(resolved)) => *text = resolved,
Ok(None) => {}
Err(detail) => problems.push(Problem { origin: Some(origin.clone()), detail }),
});
}
fn value_at<'v>(value: &'v Value, path: &[&str]) -> Option<&'v Value> {
path.iter().try_fold(value, |value, name| match value {
Value::Object(map) => map.get(*name),
Value::Array(items) => items.get(name.parse::<usize>().ok()?),
_ => None,
})
}
fn holder<'f>(factories: &[&'f PackageFactory], feature: &str) -> Option<&'f PackageFactory> {
factories.iter().copied().find(|factory| factory.features().iter().any(|entry| entry.name == feature))
}
pub fn declaration_in_force<'f>(
factories: &[&'f PackageFactory],
feature: &str,
off: impl Fn(&str) -> bool,
) -> Option<Cow<'f, SettingsDecl>> {
entries_in_force(factories, feature, off, &mut Vec::new())
}
fn entries_in_force<'f>(
factories: &[&'f PackageFactory],
feature: &str,
off: impl Fn(&str) -> bool,
problems: &mut Vec<String>,
) -> Option<Cow<'f, SettingsDecl>> {
let owner = holder(factories, feature)?.settings(feature)?;
let mut declared: Vec<(&Name, &str, &EntryDecl)> = Vec::new();
for factory in factories {
for entry in factory.features() {
let Some(decl) = &entry.settings else { continue };
if off(&entry.name) {
continue;
}
for declaration in decl.entries().iter().filter(|declaration| declaration.owner().as_str() == feature) {
let path = declaration.path();
if !owner.opens(path) {
problems.push(format!(
"Misconfigured feature ‘{}’: the feature ‘{feature}’ does not allow other features to \
declare an entry at ‘{feature}.{path}’",
entry.name
));
continue;
}
let label = declaration.label();
match declared.iter().find(|(_, _, other)| other.path() == path) {
Some((package, other, _)) if *package == factory.name() => problems.push(format!(
"Duplicate {label} (features ‘{other}’ and ‘{}’ of the package ‘{package}’)",
entry.name
)),
Some((package, _, _)) => problems.push(format!(
"Duplicate {label} (packages ‘{package}’ and ‘{}’)",
factory.name()
)),
None => declared.push((factory.name(), entry.name.as_str(), declaration)),
}
}
}
}
if declared.is_empty() {
return Some(Cow::Borrowed(owner));
}
Some(Cow::Owned(owner.with_entries(declared.into_iter().map(|(_, _, declaration)| declaration))))
}
fn shown(value: &Value) -> String {
format!("`{value}`")
}
impl<O: CascadeOrigin> Cascade<O> {
pub fn new() -> Cascade<O> {
Cascade::default()
}
pub fn with_reach(reach: Reach) -> Cascade<O> {
Cascade { reach, ..Cascade::default() }
}
pub fn set(&mut self, feature: &str, key: &str, value: Value, origin: O) {
let values = self.features.entry(feature.to_string()).or_default();
values.written.push(origin.clone());
values.keys.entry(key.to_string()).or_default().push(SettingValue { value, origin });
}
pub fn switch_off(&mut self, feature: &str, origin: O) {
self.switch(feature, true, origin);
}
pub fn switch_on(&mut self, feature: &str, origin: O) {
self.switch(feature, false, origin);
}
fn switch(&mut self, feature: &str, off: bool, origin: O) {
let values = self.features.entry(feature.to_string()).or_default();
values.written.push(origin.clone());
values.off.push((off, origin));
}
pub fn set_parsing(&mut self, key: &str, value: Value, origin: O) {
self.parsing.entry(key.to_string()).or_default().push((value, origin));
}
pub fn add_workflow_fields(&mut self, workflow: &str, fields: impl IntoIterator<Item = (String, Value, O)>) {
let written = self.workflow_fields.entry(workflow.to_string()).or_default();
for (field, value, origin) in fields {
written.entry(field).or_default().push((value, origin));
}
}
pub fn value(&self, feature: &str, key: &str) -> Option<SettingValue<O>> {
let written = whole(self.features.get(feature)?.keys.get(key)?, &self.reach)?;
Some(SettingValue { value: written.value, origin: written.origin })
}
pub fn switched_off(&self, feature: &str) -> Option<O> {
let off = self.decide(&self.features.get(feature)?.off)?;
if off.value { Some(off.origin) } else { None }
}
pub fn workflow_field(&self, workflow: &str, field: &str) -> Option<SettingValue<O>> {
let writes = self.workflow_fields.get(workflow)?.get(field)?;
let written = self.decide(writes)?;
Some(SettingValue { value: written.value, origin: written.origin })
}
pub fn workflows(&self) -> BTreeMap<String, Vec<(String, SettingValue<O>)>> {
self.workflow_fields
.keys()
.map(|workflow| {
let fields = self.workflow_fields[workflow]
.keys()
.filter_map(|field| Some((field.clone(), self.workflow_field(workflow, field)?)))
.collect();
(workflow.clone(), fields)
})
.collect()
}
fn declaration<'f>(
&self,
factories: &[&'f PackageFactory],
feature: &str,
problems: &mut Vec<String>,
) -> Option<Cow<'f, SettingsDecl>> {
entries_in_force(factories, feature, |name| self.switched_off(name).is_some(), problems)
}
fn decide<T: PartialEq + Clone>(&self, writes: &[(T, O)]) -> Option<Written<T, O>> {
Written::decide(writes.iter().map(|(value, origin)| (value, origin)), &self.reach)
}
pub fn parsing(&self) -> Result<FlmParsing, Vec<Problem<O>>> {
let mut problems = Vec::new();
let mut data = Map::new();
for (key, writes) in &self.parsing {
let Some(written) = self.decide(writes) else { continue };
problems.extend(written.disagreement(&format!("`parsing.{key}`"), shown, true));
data.insert(key.clone(), written.value.clone());
}
if !problems.is_empty() {
return Err(problems);
}
serde_json::from_value(Value::Object(data)).map_err(|error| {
vec![Problem { origin: None, detail: format!("each parsing setting must hold a value of its type: {error}") }]
})
}
pub fn parsing_in_effect(&self) -> BTreeMap<String, SettingValue<O>> {
self.parsing
.iter()
.filter_map(|(key, writes)| {
let written = self.decide(writes)?;
Some((key.clone(), SettingValue { value: written.value, origin: written.origin }))
})
.collect()
}
pub fn in_effect(&self, factories: &[&PackageFactory]) -> BTreeMap<String, FeatureInEffect<O>> {
let mut found = Found::default();
self.features
.iter()
.filter_map(|(feature, values)| {
holder(factories, feature)?;
let decl = self.declaration(factories, feature, &mut Vec::new());
Some((feature.clone(), self.combine(feature, values, decl.as_deref(), &mut found)))
})
.collect()
}
pub fn writes_at(
&self,
decl: Option<&SettingsDecl>,
feature: &str,
key: &str,
path: &[&str],
) -> Vec<WriteAt<O>> {
let Some(writes) = self.features.get(feature).and_then(|values| values.keys.get(key)) else {
return Vec::new();
};
let in_effect = match decl {
Some(decl) if self.switched_off(feature).is_none() => self.write_in_effect(decl, key, path, writes),
_ => None,
};
let mut found: Vec<(usize, Value)> = writes
.iter()
.enumerate()
.filter_map(|(at, write)| Some((at, value_at(&write.value, path)?.clone())))
.collect();
found.sort_by_key(|(at, _)| writes[*at].origin.rank());
found
.into_iter()
.map(|(at, value)| WriteAt { value, origin: writes[at].origin.clone(), in_effect: in_effect == Some(at) })
.collect()
}
pub fn decided_at(
&self,
decl: Option<&SettingsDecl>,
feature: &str,
key: &str,
path: &[&str],
) -> Option<DecidedAt<O>> {
let decl = decl.filter(|_| self.switched_off(feature).is_none())?;
let writes = self.features.get(feature).and_then(|values| values.keys.get(key));
let writes = writes.map(Vec::as_slice).unwrap_or_default();
let (depth, decided) = self.decide_whole(decl, key, path, writes)?;
Some(DecidedAt { depth, origin: decided.map(|(at, _)| writes[at].origin.clone()) })
}
fn write_in_effect(
&self,
decl: &SettingsDecl,
key: &str,
path: &[&str],
writes: &[SettingValue<O>],
) -> Option<usize> {
let (depth, (at, value)) = match self.decide_whole(decl, key, path, writes)? {
(depth, Some(decided)) => (depth, decided),
(_, None) => return None,
};
value_at(value, &path[depth..]).map(|_| at)
}
fn decide_whole<'w>(
&self,
decl: &SettingsDecl,
key: &str,
path: &[&str],
writes: &'w [SettingValue<O>],
) -> Option<(usize, Option<(usize, &'w Value)>)> {
let mut place = vec![key.to_string()];
let mut level: Vec<(usize, &Value)> = writes.iter().enumerate().map(|(at, write)| (at, &write.value)).collect();
while decl.is_marked(&place, Mark::MergeObjectKeyValues) {
let name = path.get(place.len() - 1)?;
level = level.into_iter().filter_map(|(at, value)| Some((at, value.as_object()?.get(*name)?))).collect();
place.push(name.to_string());
}
let candidates: Vec<(&Value, &O)> = level.iter().map(|(at, value)| (*value, &writes[*at].origin)).collect();
let decided = decide_at(&candidates, &self.reach).map(|(first, _)| level[first]);
Some((place.len() - 1, decided))
}
fn combine(
&self,
feature: &str,
values: &FeatureValues<O>,
decl: Option<&SettingsDecl>,
found: &mut Found<O>,
) -> FeatureInEffect<O> {
let mut in_effect = FeatureInEffect { switched_off: None, keys: BTreeMap::new() };
if let Some(off) = self.decide(&values.off) {
let state = |off: &bool| String::from(if *off { "`false`" } else { "settings" });
found.problems.extend(off.disagreement(&format!("the feature `{feature}`"), state, true));
if off.value {
in_effect.switched_off = Some(off.origin);
return in_effect;
}
}
let Some(decl) = decl else { return in_effect };
for (key, writes) in &values.keys {
for write in writes {
if let (Some(workflow), Some(declared)) = (write.origin.workflow(), decl.key(key)) {
if declared.bind != Bind::Render {
found.problems.push(Problem {
origin: Some(write.origin.clone()),
detail: format!("the settings of the workflow `{workflow}` must not set `{feature}.{key}`: a workflow's settings may set only keys that are set per render request, and `{feature}.{key}` is not one"),
});
}
}
}
let combiner = Combiner { feature, decl, reach: &self.reach };
let mut path = vec![key.clone()];
let written = writes.iter().map(|write| (&write.value, &write.origin)).collect();
let Some(combined) = combiner.combine(&mut path, written, None, found) else { continue };
if combined.value.is_null() && decl.is_marked(&path, Mark::SetToDefaultWithNull) {
continue;
}
let mut combined = KeyInEffect {
value: combined.value,
origin: combined.origin,
entry_origins: combined.below.entry_origins,
below: combined.below.below,
};
resolve_paths(decl, key, &mut combined, &mut found.problems);
in_effect.keys.insert(key.clone(), combined);
}
in_effect
}
pub fn read(&self, factories: &[&PackageFactory]) -> Result<ReadSettings<O>, ReadFailure<O>> {
let mut read = ReadSettings::default();
for factory in factories {
read.packages.insert(factory.name().clone(), PackageSettings::new());
}
let mut problems = Vec::new();
for (workflow, field, writes) in self
.workflow_fields
.iter()
.flat_map(|(workflow, fields)| fields.iter().map(move |(field, writes)| (workflow, field, writes)))
{
let Some(written) = self.decide(writes) else { continue };
let what = format!("the field `{field}` of the workflow `{workflow}`");
problems.extend(written.disagreement(&what, shown, false));
}
let mut written_features: BTreeMap<&str, (FeatureInEffect<O>, Option<O>)> = BTreeMap::new();
for (feature, values) in &self.features {
let first_origin = values
.keys
.values()
.find_map(|writes| writes.first())
.map(|write| write.origin.clone())
.or(values.off.first().map(|(_, origin)| origin.clone()));
let Some(factory) = holder(factories, feature) else {
let mut firsts: Vec<&O> = Vec::new();
for origin in &values.written {
if !firsts.iter().any(|first| same_source(*first, origin)) {
firsts.push(origin);
}
}
read.warnings.extend(firsts.into_iter().map(|origin| Warning {
kind: WarningKind::UnknownFeature,
problem: Problem {
origin: Some(origin.clone()),
detail: format!("Unknown feature ‘{feature}’: no package in use has this feature"),
},
}));
continue;
};
let decl = self.declaration(factories, feature, &mut Vec::new()).filter(|decl| decl.takes_settings());
let mut found = Found::default();
let in_effect = self.combine(feature, values, decl.as_deref(), &mut found);
problems.extend(found.problems);
read.warnings.extend(found.warnings);
if in_effect.switched_off.is_some() {
read.packages.entry(factory.name().clone()).or_default().switch_off(feature.as_str());
} else if decl.is_some() {
written_features.insert(feature.as_str(), (in_effect, first_origin));
} else if !values.keys.is_empty() {
problems.push(Problem {
origin: first_origin,
detail: format!("the feature `{feature}` takes no settings, so nothing may be written under it"),
});
}
}
for factory in factories {
let package = read.packages.entry(factory.name().clone()).or_default();
for entry in factory.features() {
if entry.settings.is_none() || package.is_off(&entry.name) {
continue;
}
let mut declared = Vec::new();
let Some(decl) = self.declaration(factories, &entry.name, &mut declared) else { continue };
problems.extend(declared.into_iter().map(|detail| Problem { origin: None, detail }));
let (in_effect, first_origin) = match written_features.get(entry.name.as_str()) {
Some((in_effect, first_origin)) => (Some(in_effect), first_origin.as_ref()),
None => (None, None),
};
let data: Map<String, Value> = in_effect
.iter()
.flat_map(|in_effect| &in_effect.keys)
.map(|(key, combined)| (key.clone(), combined.value.clone()))
.collect();
match decl.read(&data) {
Ok(settings) => {
read.document.merge_from(settings.document_options());
read.render.merge_from(settings.render_options());
package.insert(settings);
}
Err(errors) => problems.extend(errors.into_iter().map(|error| {
let mut path = error.path.split('.').skip(1);
let at = path.next().and_then(|key| in_effect?.keys.get(key)).map(|combined| {
let below: Vec<&str> = path.collect();
combined.origin_at(&below).clone()
});
Problem { origin: at.or_else(|| first_origin.cloned()), detail: error.detail }
})),
}
}
}
if problems.is_empty() { Ok(read) } else { Err(ReadFailure { errors: problems, warnings: read.warnings }) }
}
}
pub fn workflow_def<'v>(name: &str, fields: impl IntoIterator<Item = (&'v str, &'v Value)>) -> WorkflowDef {
let mut def = WorkflowDef::new(name);
let names = |value: &Value| -> Vec<String> {
value.as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect()
};
for (field, value) in fields {
match field {
"extends" => def.extends = value.as_str().map(Into::into),
"outputs" => def.outputs = names(value).into_iter().map(Into::into).collect(),
"demands" => def.demands = names(value).into_iter().map(Into::into).collect(),
"prefer" => def.prefer = names(value).into_iter().map(Into::into).collect(),
"docs" => def = def.docs(value.as_str().unwrap_or_default()),
_ => {}
}
}
def
}