use std::any::Any;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::sync::{Arc, OnceLock};
use serde::de::DeserializeOwned;
use serde_json::{Map, Value};
use crate::core::registry::{BuildError, FeatureBuilder};
use crate::model::names::{FeatureName, Name};
use crate::model::options::{Bind, DataValue, OptionKey, Options, OptionValues};
pub mod cascade;
mod marks;
pub mod named;
pub const ENABLED_KEY: &str = "enabled";
pub trait SettingsData: DeserializeOwned + schemars::JsonSchema + Any + Send + Sync {}
impl<T: DeserializeOwned + schemars::JsonSchema + Any + Send + Sync> SettingsData for T {}
pub const MARKS_KEYWORD: &str = "x-flm-marks";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Mark {
MergeObjectKeyValues,
RemoveKeyWhenValueIsFalse,
SetToDefaultWithNull,
Path,
Markup,
}
impl Mark {
pub const ALL: [Mark; 5] =
[Mark::MergeObjectKeyValues, Mark::RemoveKeyWhenValueIsFalse, Mark::SetToDefaultWithNull, Mark::Path, Mark::Markup];
pub fn name(self) -> &'static str {
match self {
Mark::MergeObjectKeyValues => "merge-object-key-values",
Mark::RemoveKeyWhenValueIsFalse => "remove-key-when-value-is-false",
Mark::SetToDefaultWithNull => "set-to-default-with-null",
Mark::Path => "path",
Mark::Markup => "markup",
}
}
pub fn from_name(name: &str) -> Option<Mark> {
Mark::ALL.into_iter().find(|mark| mark.name() == name)
}
}
impl fmt::Display for Mark {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyMark {
pub path: String,
pub marks: Vec<Mark>,
}
impl KeyMark {
pub fn has(&self, mark: Mark) -> bool {
self.marks.contains(&mark)
}
}
pub(crate) fn rewrite_marked(
schema: &Value,
mark: Mark,
data: &mut Map<String, Value>,
rewrite: &mut dyn FnMut(&str) -> Result<String, String>,
) -> Result<(), String> {
let Ok(read) = marks::read(schema) else { return Ok(()) };
let mut failed = None;
for node in read.iter().filter(|node| node.marks.contains(&mark)) {
let mut segments = node.path.split('.');
let Some(value) = segments.next().and_then(|key| data.get_mut(key)) else { continue };
let below: Vec<&str> = segments.collect();
texts_at(value, &below, &mut |text| {
if failed.is_some() {
return;
}
match rewrite(text) {
Ok(rewritten) => *text = rewritten,
Err(error) => failed = Some(error),
}
});
}
failed.map_or(Ok(()), Err)
}
pub(crate) fn texts_at(value: &mut Value, segments: &[&str], visit: &mut dyn FnMut(&mut String)) {
match (segments.split_first(), value) {
(None, Value::String(text)) => visit(text),
(None, Value::Array(items)) => items.iter_mut().for_each(|item| texts_at(item, &[], visit)),
(None, Value::Object(map)) => map.values_mut().for_each(|item| texts_at(item, &[], visit)),
(Some((&"*", rest)), Value::Array(items)) => items.iter_mut().for_each(|item| texts_at(item, rest, visit)),
(Some((&"*", rest)), Value::Object(map)) => map.values_mut().for_each(|item| texts_at(item, rest, visit)),
(Some((name, rest)), Value::Object(map)) => {
if let Some(item) = map.get_mut(*name) {
texts_at(item, rest, visit);
}
}
_ => {}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyDecl {
pub name: String,
pub bind: Bind,
}
type ReadFn = Arc<dyn Fn(Value) -> Result<ReadValue, ReadError> + Send + Sync>;
type DeclareFn = Arc<dyn Fn(&mut FeatureBuilder<'_>, Bind, String) -> Result<(), BuildError> + Send + Sync>;
type SchemaFn = Arc<dyn Fn(&mut schemars::SchemaGenerator) -> schemars::Schema + Send + Sync>;
#[derive(Clone)]
struct Part {
bind: Bind,
option: OptionKey,
docs: String,
keys: Vec<String>,
read: ReadFn,
declare: DeclareFn,
schema: SchemaFn,
}
enum ReadValue {
Config(Arc<dyn Any + Send + Sync>),
Option(Box<dyn FnOnce(&mut OptionValues)>),
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ReadError {
#[serde(default)]
pub path: String,
pub detail: String,
}
#[derive(Clone)]
pub struct SettingsDecl {
feature: FeatureName,
parts: Vec<Part>,
marks: Vec<KeyMark>,
defaults: Vec<(String, Map<String, Value>)>,
open: Vec<String>,
entries: Vec<EntryDecl>,
in_force: Vec<EntryDecl>,
bare: OnceLock<Arc<Value>>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct EntryDecl {
owner: FeatureName,
path: String,
label: String,
schema: Value,
keys: Vec<String>,
marks: Vec<KeyMark>,
defaults: Vec<(String, Map<String, Value>)>,
}
impl EntryDecl {
pub fn owner(&self) -> &FeatureName {
&self.owner
}
pub fn path(&self) -> &str {
&self.path
}
pub fn label(&self) -> &str {
&self.label
}
pub fn keys(&self) -> &[String] {
&self.keys
}
}
pub type DefaultEntries = fn() -> Result<Value, String>;
impl SettingsDecl {
pub fn new(feature: impl Into<FeatureName>) -> SettingsDecl {
SettingsDecl {
feature: feature.into(),
parts: Vec::new(),
marks: Vec::new(),
defaults: Vec::new(),
open: Vec::new(),
entries: Vec::new(),
in_force: Vec::new(),
bare: OnceLock::new(),
}
}
pub fn config<C: SettingsData + Options>(self, docs: impl Into<String>) -> SettingsDecl {
self.config_from::<C, C>(docs)
}
pub fn config_from<D, C>(self, docs: impl Into<String>) -> SettingsDecl
where
D: SettingsData,
C: Options + TryFrom<D>,
<C as TryFrom<D>>::Error: fmt::Display,
{
fn read<D, C>(data: Value) -> Result<ReadValue, ReadError>
where
D: SettingsData,
C: Options + TryFrom<D>,
<C as TryFrom<D>>::Error: fmt::Display,
{
let value = deserialize::<D>(data)?;
let config = C::try_from(value)
.map_err(|error| ReadError { path: String::new(), detail: error.to_string() })?;
Ok(ReadValue::Config(Arc::new(config)))
}
fn declare<C: Options>(
b: &mut FeatureBuilder<'_>,
bind: Bind,
docs: String,
) -> Result<(), BuildError> {
b.options_with_docs::<C>(bind, docs)
}
self.part(Part {
bind: Bind::Registry,
option: OptionKey::of::<C>(),
docs: crate::kept_docs(docs),
keys: field_names::<D>(),
read: Arc::new(read::<D, C>),
declare: Arc::new(declare::<C>),
schema: Arc::new(|generator: &mut schemars::SchemaGenerator| generator.subschema_for::<D>()),
})
}
pub fn config_data(self, schema: Value, docs: impl Into<String>) -> Result<SettingsDecl, SettingsError> {
self.data_config(schema, docs.into(), Arc::new(|data: Value| Ok(ReadValue::Config(Arc::new(DataValue(data))))))
}
pub fn config_data_read(
self,
schema: Value,
docs: impl Into<String>,
read: Arc<dyn Fn(Value) -> Result<Value, ReadError> + Send + Sync>,
) -> Result<SettingsDecl, SettingsError> {
let read: ReadFn = Arc::new(move |data: Value| Ok(ReadValue::Config(Arc::new(DataValue(read(data)?)))));
self.data_config(schema, docs.into(), read)
}
fn data_config(self, schema: Value, docs: String, read: ReadFn) -> Result<SettingsDecl, SettingsError> {
let feature = self.feature.clone();
let keys = schema_keys(&schema).ok_or_else(|| {
self.invalid(
String::new(),
format!(
"the schema of the configuration of the feature `{feature}` must be an object \
schema with `properties`, a map from each setting to its schema"
),
)
})?;
let name = Name::clone(&feature);
self.try_part(Part {
bind: Bind::Registry,
option: OptionKey::Data(name.clone()),
docs: crate::kept_docs(docs),
keys,
read,
declare: declare_named(name),
schema: data_schema(schema.clone()),
})?
.with_read_marks(&schema)
}
pub fn options_data(
self,
name: impl Into<Name>,
bind: Bind,
schema: Value,
docs: impl Into<String>,
) -> Result<SettingsDecl, SettingsError> {
let name = name.into();
let feature = self.feature.clone();
if bind == Bind::Registry {
return Err(self.invalid(
String::new(),
format!(
"the feature `{feature}` declares the option `{name}` bound to the registry, \
and a value fixed when the registry is built belongs in the feature's \
configuration"
),
));
}
let keys = schema_keys(&schema).ok_or_else(|| {
self.invalid(
String::new(),
format!(
"the schema of the option `{name}` of the feature `{feature}` must be an object \
schema with `properties`, a map from each setting to its schema"
),
)
})?;
let read_name = name.clone();
self.try_part(Part {
bind,
option: OptionKey::Data(name.clone()),
docs: crate::kept_docs(docs),
keys,
read: Arc::new(move |data: Value| {
let name = read_name.clone();
Ok(ReadValue::Option(Box::new(move |values: &mut OptionValues| values.set_named(name, data))))
}),
declare: declare_named(name),
schema: data_schema(schema.clone()),
})?
.with_read_marks(&schema)
}
pub fn options<O: SettingsData + Options>(
self,
bind: Bind,
docs: impl Into<String>,
) -> SettingsDecl {
assert!(
bind != Bind::Registry,
"the feature `{}` declares the option type `{}` with `Bind::Registry`, but the values \
of an option type must be set on the document or on the render request; a value \
fixed when the registry is built belongs in the feature's configuration, declared \
with `SettingsDecl::config`",
self.feature,
crate::model::options::short_type_name(std::any::type_name::<O>())
);
fn read<O: SettingsData + Options>(data: Value) -> Result<ReadValue, ReadError> {
let value = deserialize::<O>(data)?;
Ok(ReadValue::Option(Box::new(move |values: &mut OptionValues| values.set::<O>(value))))
}
fn declare<O: Options>(
b: &mut FeatureBuilder<'_>,
bind: Bind,
docs: String,
) -> Result<(), BuildError> {
b.options_with_docs::<O>(bind, docs)
}
self.part(Part {
bind,
option: OptionKey::of::<O>(),
docs: crate::kept_docs(docs),
keys: field_names::<O>(),
read: Arc::new(read::<O>),
declare: Arc::new(declare::<O>),
schema: Arc::new(|generator: &mut schemars::SchemaGenerator| generator.subschema_for::<O>()),
})
}
fn part(self, part: Part) -> SettingsDecl {
match self.try_part(part) {
Ok(decl) => decl,
Err(error) => panic!("{}", error.detail),
}
}
fn try_part(mut self, part: Part) -> Result<SettingsDecl, SettingsError> {
if part.keys.iter().any(|key| key == ENABLED_KEY) {
let detail = format!(
"the feature ‘{}’ declares the setting ‘{ENABLED_KEY}’, a name reserved for \
switching a feature on or off",
self.feature
);
return Err(self.invalid(ENABLED_KEY.to_string(), detail));
}
for key in &part.keys {
if self.part_of(key).is_some() {
let detail = format!("the feature `{}` declares the setting `{key}` twice", self.feature);
return Err(self.invalid(key.clone(), detail));
}
}
if part.bind == Bind::Registry && self.parts.iter().any(|p| p.bind == Bind::Registry) {
let detail = format!("the feature `{}` declares two configurations", self.feature);
return Err(self.invalid(String::new(), detail));
}
self.parts.push(part);
self.bare = OnceLock::new();
Ok(self)
}
fn invalid(&self, path: String, detail: String) -> SettingsError {
let path = if path.is_empty() { self.feature.to_string() } else { format!("{}.{path}", self.feature) };
SettingsError { path, kind: SettingsErrorKind::InvalidDeclaration, detail }
}
pub fn merge_entries(self, path: impl Into<String>, default_entries: DefaultEntries) -> SettingsDecl {
let path = path.into();
let decl = self.mark(path.clone(), Mark::MergeObjectKeyValues);
let entries = match default_entries() {
Ok(Value::Object(entries)) => entries,
Ok(other) => panic!(
"the default entries of ‘{}.{path}’ must be written as a map, not ‘{other}’",
decl.feature
),
Err(detail) => panic!(
"the default entries of ‘{}.{path}’ cannot be written as data: {detail}",
decl.feature
),
};
decl.with_default(path, entries)
}
fn with_default(mut self, path: String, entries: Map<String, Value>) -> SettingsDecl {
self.defaults.retain(|(marked, _)| *marked != path);
self.defaults.push((path, entries));
self
}
pub fn default_entries(&self, path: &str) -> Option<&Map<String, Value>> {
self.defaults.iter().find(|(marked, _)| marked == path).map(|(_, entries)| entries)
}
pub fn remove_false(self, path: impl Into<String>) -> SettingsDecl {
self.mark(path.into(), Mark::RemoveKeyWhenValueIsFalse)
}
pub fn default_on_null(self, path: impl Into<String>) -> SettingsDecl {
self.mark(path.into(), Mark::SetToDefaultWithNull)
}
pub fn markup(self, path: impl Into<String>) -> SettingsDecl {
self.mark(path.into(), Mark::Markup)
}
pub fn path(self, path: impl Into<String>) -> SettingsDecl {
self.mark(path.into(), Mark::Path)
}
fn mark(self, path: String, mark: Mark) -> SettingsDecl {
let bare = Arc::clone(self.bare.get_or_init(|| Arc::new(self.bare_schema())));
if !marks::reaches(&bare, &path) {
panic!("missing setting ‘{path}’ for the mark ‘{mark}’ of the feature ‘{}’", self.feature);
}
self.with_mark(path, mark)
}
fn with_mark(mut self, path: String, mark: Mark) -> SettingsDecl {
match self.marks.iter_mut().find(|marked| marked.path == path) {
Some(marked) => {
if !marked.has(mark) {
marked.marks.push(mark);
marked.marks.sort();
}
}
None => self.marks.push(KeyMark { path, marks: vec![mark] }),
}
self
}
fn with_read_marks(mut self, schema: &Value) -> Result<SettingsDecl, SettingsError> {
let read = read_marks(schema, &self.feature, "", &format!("the feature ‘{}’", self.feature))?;
for written in read {
for mark in written.marks {
self = self.with_mark(written.path.clone(), mark);
}
if let Some(entries) = written.default {
self = self.with_default(written.path, entries);
}
}
Ok(self)
}
pub fn open_entries(self, path: impl Into<String>) -> SettingsDecl {
let path = path.into();
let bare = Arc::clone(self.bare.get_or_init(|| Arc::new(self.bare_schema())));
if !marks::reaches(&bare, &path) {
panic!("missing setting ‘{path}’ for the entries that the feature ‘{}’ opens", self.feature);
}
let mut decl = self;
if !decl.open.contains(&path) {
decl.open.push(path);
}
decl
}
pub fn opens(&self, path: &str) -> bool {
let segments: Vec<String> = path.split('.').map(str::to_string).collect();
self.open.iter().any(|open| cascade::names(open, &segments))
}
pub fn entry_data(
mut self,
owner: impl Into<FeatureName>,
path: impl Into<String>,
label: impl Into<String>,
schema: Value,
) -> Result<SettingsDecl, SettingsError> {
let (owner, path, label) = (owner.into(), path.into(), label.into());
let at = |detail: String| SettingsError {
path: format!("{owner}.{path}"),
kind: SettingsErrorKind::InvalidDeclaration,
detail,
};
if path.split('.').any(|segment| segment.is_empty() || segment == "*") {
return Err(at(format!(
"Invalid entry ‘{owner}.{path}’ declared by the feature ‘{}’: each part of the path must name one entry",
self.feature
)));
}
if self.entries.iter().any(|entry| entry.owner == owner && entry.path == path) {
return Err(at(format!("Duplicate {label} (feature ‘{}’)", self.feature)));
}
let Some(keys) = schema_keys(&schema) else {
return Err(at(format!(
"Invalid settings schema of the {label}: it must be an object schema with ‘properties’, a map \
from each setting to its schema"
)));
};
let mut marks: Vec<KeyMark> = Vec::new();
let mut defaults = Vec::new();
for written in read_marks(&schema, &owner, &path, &format!("the {label}"))? {
match marks.iter_mut().find(|marked| marked.path == written.path) {
Some(marked) => {
marked.marks.extend(written.marks);
marked.marks.sort();
marked.marks.dedup();
}
None => marks.push(KeyMark { path: written.path.clone(), marks: written.marks }),
}
if let Some(entries) = written.default {
defaults.push((written.path, entries));
}
}
self.entries.push(EntryDecl { owner, path, label, schema, keys, marks, defaults });
Ok(self)
}
pub fn entries(&self) -> &[EntryDecl] {
&self.entries
}
pub fn with_entries<'e>(&self, entries: impl IntoIterator<Item = &'e EntryDecl>) -> SettingsDecl {
let mut decl = self.clone();
for entry in entries {
if entry.owner != self.feature || !self.opens(&entry.path) || decl.entry_in_force(&entry.path).is_some() {
continue;
}
let segments: Vec<String> = entry.path.split('.').map(str::to_string).collect();
for depth in 2..=segments.len() {
let place = &segments[..depth];
let concrete = place.join(".");
let owned: Vec<KeyMark> =
self.marks.iter().filter(|marked| cascade::names(&marked.path, place)).cloned().collect();
for marked in owned {
for mark in &marked.marks {
decl = decl.with_mark(concrete.clone(), *mark);
}
if let Some(entries) = self.default_entries(&marked.path) {
decl = decl.with_default(concrete.clone(), entries.clone());
}
}
}
for marked in &entry.marks {
for mark in &marked.marks {
decl = decl.with_mark(format!("{}.{}", entry.path, marked.path), *mark);
}
}
for (path, entries) in &entry.defaults {
decl = decl.with_default(format!("{}.{path}", entry.path), entries.clone());
}
decl.in_force.push(entry.clone());
}
decl
}
pub fn entry_in_force(&self, path: &str) -> Option<&EntryDecl> {
self.in_force.iter().find(|entry| entry.path == path)
}
}
fn read_marks(
schema: &Value,
feature: &FeatureName,
prefix: &str,
holder: &str,
) -> Result<Vec<marks::ReadMark>, SettingsError> {
let full = |path: &str| match (prefix.is_empty(), path.is_empty()) {
(true, _) => path.to_string(),
(false, true) => prefix.to_string(),
(false, false) => format!("{prefix}.{path}"),
};
marks::read(schema).map_err(|fault| {
let (path, detail) = match fault {
marks::Fault::NotAList(path) => {
let detail = format!("‘{MARKS_KEYWORD}’ on ‘{path}’ of {holder} must be a list of mark names");
(full(&path), detail)
}
marks::Fault::Unknown(path, name) => {
let names: Vec<String> = Mark::ALL.iter().map(|mark| format!("‘{mark}’")).collect();
let detail = format!("unknown mark ‘{name}’ on ‘{path}’ of {holder} (the marks are {})", names.join(", "));
(full(&path), detail)
}
marks::Fault::DefaultNotAMap(path) => {
let detail = format!(
"the default of ‘{path}’ of {holder} must be a map (mark ‘{}’)",
Mark::MergeObjectKeyValues
);
(full(&path), detail)
}
marks::Fault::Outside(pointer) => {
let place = if pointer.is_empty() { "on the root".to_string() } else { format!("at ‘{pointer}’") };
let detail = format!(
"misplaced ‘{MARKS_KEYWORD}’ {place} of the settings schema of {holder}: marks must be written on \
a setting or on a value below one"
);
(prefix.to_string(), detail)
}
marks::Fault::Recursive(path, definition) => {
let detail = format!(
"invalid mark on ‘{path}’ of {holder}: \
marks may not be placed inside the recursive definition ‘{definition}’"
);
(full(&path), detail)
}
};
let path = if path.is_empty() { feature.to_string() } else { format!("{feature}.{path}") };
SettingsError { path, kind: SettingsErrorKind::InvalidDeclaration, detail }
})
}
impl SettingsDecl {
pub fn feature(&self) -> &FeatureName {
&self.feature
}
pub fn keys(&self) -> impl Iterator<Item = KeyDecl> + '_ {
self.parts
.iter()
.flat_map(|part| part.keys.iter().map(|name| KeyDecl { name: name.clone(), bind: part.bind }))
}
pub fn takes_settings(&self) -> bool {
self.keys().next().is_some()
}
pub fn option_types(&self) -> impl Iterator<Item = (OptionKey, Bind)> + '_ {
self.parts.iter().map(|part| (part.option.clone(), part.bind))
}
pub fn key(&self, name: &str) -> Option<KeyDecl> {
self.keys().find(|key| key.name == name)
}
pub fn marks(&self) -> &[KeyMark] {
&self.marks
}
pub fn is_marked(&self, place: &[String], mark: Mark) -> bool {
self.marks.iter().any(|marks| marks.has(mark) && cascade::names(&marks.path, place))
}
pub fn mark_at(&self, path: &str) -> Option<&KeyMark> {
self.marks.iter().find(|mark| mark.path == path)
}
pub fn has_mark(&self, path: &str, mark: Mark) -> bool {
self.mark_at(path).is_some_and(|marked| marked.has(mark))
}
fn part_of(&self, key: &str) -> Option<&Part> {
self.parts.iter().find(|part| part.keys.iter().any(|name| name == key))
}
pub fn read(&self, data: &Map<String, Value>) -> Result<FeatureSettings, Vec<SettingsError>> {
let mut errors = Vec::new();
for key in data.keys() {
if self.part_of(key).is_none() {
errors.push(SettingsError {
path: format!("{}.{key}", self.feature),
kind: SettingsErrorKind::UnknownKey,
detail: format!("the feature `{}` has no setting `{key}`", self.feature),
});
}
}
let mut settings = FeatureSettings {
feature: self.feature.clone(),
config: None,
document: OptionValues::new(),
render: OptionValues::new(),
};
for part in &self.parts {
let written: Map<String, Value> = data
.iter()
.filter(|(key, _)| part.keys.iter().any(|name| name == *key))
.map(|(key, value)| (key.clone(), value.clone()))
.collect();
if written.is_empty() && part.bind != Bind::Registry {
continue;
}
match (part.read)(Value::Object(written)) {
Ok(ReadValue::Config(config)) => settings.config = Some(config),
Ok(ReadValue::Option(set)) => {
let values = match part.bind {
Bind::Render => &mut settings.render,
_ => &mut settings.document,
};
set(values);
}
Err(error) => {
let path = if error.path.is_empty() {
self.feature.to_string()
} else {
format!("{}.{}", self.feature, error.path)
};
errors.push(SettingsError {
detail: format!("the value of `{path}` is invalid: {}", error.detail),
path,
kind: SettingsErrorKind::InvalidValue,
});
}
}
}
if errors.is_empty() { Ok(settings) } else { Err(errors) }
}
pub(crate) fn declare(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
for part in &self.parts {
(part.declare)(b, part.bind, part.docs.clone())?;
}
Ok(())
}
pub fn json_schema(&self) -> Value {
let mut root = self.bare_schema();
for entry in &self.in_force {
marks::graft(&mut root, &entry.path, &entry.schema);
}
marks::print(&mut root, &self.marks, |path| self.default_entries(path));
plain_descriptions(&mut root);
root
}
fn bare_schema(&self) -> Value {
let mut generator = schemars::SchemaGenerator::default();
let mut properties = Map::new();
for part in &self.parts {
let schema = (part.schema)(&mut generator);
let resolved = resolve_ref(&generator, schema.as_value());
let fields = resolved.get("properties").and_then(Value::as_object);
for key in &part.keys {
let mut property =
fields.and_then(|fields| fields.get(key)).cloned().unwrap_or(Value::Bool(true));
if let Value::Object(object) = &mut property {
object.insert("x-flm-bind".into(), Value::from(part.bind.label()));
} else {
let mut object = Map::new();
object.insert("x-flm-bind".into(), Value::from(part.bind.label()));
property = Value::Object(object);
}
properties.insert(key.clone(), property);
}
}
let mut root = Map::new();
let docs: Vec<&str> = self.parts.iter().map(|part| part.docs.as_str()).filter(|docs| !docs.is_empty()).collect();
if !docs.is_empty() {
root.insert("description".into(), Value::from(docs.join("\n\n")));
}
root.insert("type".into(), Value::from("object"));
root.insert("properties".into(), Value::Object(properties));
root.insert("additionalProperties".into(), Value::Bool(false));
let definitions = generator.take_definitions(true);
if !definitions.is_empty() {
root.insert("$defs".into(), Value::Object(definitions));
}
Value::Object(root)
}
}
impl fmt::Debug for SettingsDecl {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SettingsDecl")
.field("feature", &self.feature)
.field("keys", &self.keys().map(|key| key.name).collect::<Vec<_>>())
.field("marks", &self.marks)
.finish()
}
}
pub fn schema_of<T: schemars::JsonSchema>() -> Value {
let mut schema = schemars::SchemaGenerator::default().into_root_schema_for::<T>().to_value();
if let Value::Object(object) = &mut schema {
object.remove("$schema");
object.remove("title");
}
plain_descriptions(&mut schema);
schema
}
fn plain_descriptions(schema: &mut Value) {
match schema {
Value::Object(object) => {
for (keyword, value) in object.iter_mut() {
match (keyword.as_str(), value) {
("description", Value::String(text)) => *text = plain_text(text),
("default" | "const" | "enum" | "examples", _) => {}
(keyword, _) if keyword.starts_with("x-flm-") => {}
(_, value) => plain_descriptions(value),
}
}
}
Value::Array(items) => items.iter_mut().for_each(plain_descriptions),
_ => {}
}
}
fn plain_text(doc: &str) -> String {
let mut lines = Vec::new();
let mut in_code_block = false;
for line in doc.lines() {
let trimmed = line.trim_start();
if trimmed.starts_with("```") {
in_code_block = !in_code_block;
continue;
}
if in_code_block {
continue;
}
if trimmed.starts_with('#') && trimmed.trim_start_matches('#').starts_with(' ') {
break;
}
lines.push(line);
}
let mut text = String::new();
for line in unlinked(&lines.join("\n")).lines() {
if line.trim().is_empty() && (text.is_empty() || text.ends_with("\n\n")) {
continue;
}
text.push_str(line);
text.push('\n');
}
text.trim_end().to_string()
}
fn unlinked(text: &str) -> String {
let chars: Vec<char> = text.chars().collect();
let mut out = String::new();
let mut i = 0;
while i < chars.len() {
if chars[i] == '`' {
let end = code_span_end(&chars, i);
out.extend(&chars[i..end]);
i = end;
} else if chars[i] == '[' {
let Some(close) = closing(&chars, i, '[', ']') else {
out.push('[');
i += 1;
continue;
};
let words: String = chars[i + 1..close].iter().collect();
let target = match chars.get(close + 1) {
Some('(') => closing(&chars, close + 1, '(', ')'),
Some('[') => closing(&chars, close + 1, '[', ']'),
_ if words.starts_with('`') && words.ends_with('`') => Some(close),
_ => None,
};
match target {
Some(end) => {
out.push_str(&unlinked(&words));
i = end + 1;
}
None => {
out.push('[');
i += 1;
}
}
} else {
out.push(chars[i]);
i += 1;
}
}
out
}
fn code_span_end(chars: &[char], start: usize) -> usize {
let run = |at: usize| chars[at..].iter().take_while(|c| **c == '`').count();
let length = run(start);
let mut at = start + length;
while at < chars.len() {
if chars[at] == '`' {
let found = run(at);
if found == length {
return at + found;
}
at += found;
} else {
at += 1;
}
}
start + length
}
fn closing(chars: &[char], start: usize, open: char, close: char) -> Option<usize> {
let mut depth = 0;
let mut at = start;
while at < chars.len() {
let c = chars[at];
if c == '`' {
at = code_span_end(chars, at);
continue;
}
if c == open {
depth += 1;
} else if c == close {
depth -= 1;
if depth == 0 {
return Some(at);
}
}
at += 1;
}
None
}
fn resolve_ref(generator: &schemars::SchemaGenerator, schema: &Value) -> Value {
if let Some(reference) = schema.get("$ref").and_then(Value::as_str) {
let name = reference.rsplit('/').next().unwrap_or(reference);
if let Some(found) = generator.definitions().get(name) {
return found.clone();
}
}
schema.clone()
}
fn schema_keys(schema: &Value) -> Option<Vec<String>> {
schema.get("properties").and_then(Value::as_object).map(|properties| properties.keys().cloned().collect())
}
fn declare_named(name: Name) -> DeclareFn {
Arc::new(move |b: &mut FeatureBuilder<'_>, bind: Bind, docs: String| b.options_named(name.clone(), bind, docs))
}
fn data_schema(schema: Value) -> SchemaFn {
Arc::new(move |generator: &mut schemars::SchemaGenerator| {
let mut schema = schema.clone();
if let Some(Value::Object(definitions)) = schema.as_object_mut().and_then(|object| object.remove("$defs")) {
generator.definitions_mut().extend(definitions);
}
schemars::Schema::try_from(schema).unwrap_or_default()
})
}
fn deserialize<T: DeserializeOwned>(data: Value) -> Result<T, ReadError> {
serde_path_to_error::deserialize::<_, T>(data).map_err(|error| {
let path = error.path().to_string();
let path = if path == "." { String::new() } else { path };
ReadError { path, detail: error.into_inner().to_string() }
})
}
fn field_names<T: DeserializeOwned>() -> Vec<String> {
let mut probe = FieldProbe { fields: None };
let _ = T::deserialize(&mut probe);
probe
.fields
.unwrap_or_else(|| panic!("`{}` is not read from named fields", std::any::type_name::<T>()))
.iter()
.map(|name| (*name).to_string())
.collect()
}
struct FieldProbe {
fields: Option<&'static [&'static str]>,
}
#[derive(Debug)]
struct ProbeError;
impl fmt::Display for ProbeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("field probe")
}
}
impl std::error::Error for ProbeError {}
impl serde::de::Error for ProbeError {
fn custom<T: fmt::Display>(_msg: T) -> ProbeError {
ProbeError
}
}
impl<'de> serde::Deserializer<'de> for &mut FieldProbe {
type Error = ProbeError;
fn deserialize_any<V: serde::de::Visitor<'de>>(self, _visitor: V) -> Result<V::Value, ProbeError> {
Err(ProbeError)
}
fn deserialize_struct<V: serde::de::Visitor<'de>>(
self,
_name: &'static str,
fields: &'static [&'static str],
_visitor: V,
) -> Result<V::Value, ProbeError> {
self.fields = Some(fields);
Err(ProbeError)
}
serde::forward_to_deserialize_any! {
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
bytes byte_buf option unit unit_struct newtype_struct seq tuple
tuple_struct map enum identifier ignored_any
}
}
#[derive(Clone)]
pub struct FeatureSettings {
feature: FeatureName,
config: Option<Arc<dyn Any + Send + Sync>>,
document: OptionValues,
render: OptionValues,
}
impl FeatureSettings {
pub fn feature(&self) -> &FeatureName {
&self.feature
}
pub fn config<C: Any>(&self) -> Option<&C> {
self.config.as_deref().and_then(|config| config.downcast_ref::<C>())
}
pub fn document_options(&self) -> &OptionValues {
&self.document
}
pub fn render_options(&self) -> &OptionValues {
&self.render
}
}
impl fmt::Debug for FeatureSettings {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FeatureSettings")
.field("feature", &self.feature)
.field("config", &self.config.is_some())
.field("document", &self.document)
.field("render", &self.render)
.finish()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SettingsErrorKind {
UnknownKey,
InvalidValue,
InvalidDeclaration,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SettingsError {
pub path: String,
pub kind: SettingsErrorKind,
pub detail: String,
}
impl fmt::Display for SettingsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.detail)
}
}
impl std::error::Error for SettingsError {}
#[derive(Debug, Clone, Default)]
pub struct PackageSettings {
features: BTreeMap<FeatureName, FeatureSettings>,
off: BTreeSet<FeatureName>,
}
impl PackageSettings {
pub fn new() -> PackageSettings {
PackageSettings::default()
}
pub fn insert(&mut self, settings: FeatureSettings) -> &mut PackageSettings {
self.features.insert(settings.feature.clone(), settings);
self
}
pub fn switch_off(&mut self, feature: impl Into<FeatureName>) -> &mut PackageSettings {
self.off.insert(feature.into());
self
}
pub fn is_off(&self, feature: &str) -> bool {
self.off.contains(feature)
}
pub fn feature(&self, feature: &str) -> Option<&FeatureSettings> {
self.features.get(feature)
}
pub fn config<C: Any>(&self, feature: &str) -> Option<&C> {
self.feature(feature).and_then(FeatureSettings::config::<C>)
}
}