Skip to main content

flm_core/stdlib/features/metadata/
data.rs

1//! The metadata written as data: how a program that holds the author's metadata as a
2//! map of data values (for example the root keys of a front matter) makes the
3//! document's [`DocMeta`] from it, with [`DocMeta::from_data`].
4//!
5//! The form is the same for every program:
6//!
7//! | Key | Its value |
8//! |---|---|
9//! | [`TITLE_KEY`] (`title`) | one text |
10//! | [`AUTHOR_KEY`] (`author`) | one author, or a list of authors |
11//! | [`DATE_KEY`] (`date`) | one text |
12//! | any other key | any data, kept in [`DocMeta::other`] |
13//!
14//! An author ([`MetaAuthor`]) is a text, the author's name, or a map:
15//!
16//! | Key | Its value |
17//! |---|---|
18//! | [`NAME_KEY`] (`name`) | one text; required |
19//! | [`AFFILIATION_KEY`] (`affiliation`) | one text, or a list of texts |
20//! | [`EMAIL_KEY`] (`email`) | one text, a plain address |
21//! | [`NOTE_KEY`] (`note`) | one text, or a list of texts |
22//! | any other key | any data, kept in [`MetaAuthor::other`] |
23//!
24//! ```yaml
25//! author:
26//!   - name: 'Ada Lovelace'
27//!     affiliation: ['University of X', 'Institute of Y']
28//!     email: 'ada@example.com'
29//!     note: 'Corresponding author'
30//!   - 'Grace Hopper'
31//! ```
32//!
33//! Where a text is expected, a number or a truth value is read as the text it is
34//! written as (`date: 2026` is the text `2026`). A value of another shape, and an
35//! author's map without `name`, are errors ([`MetaDataError`]). The texts are FLM,
36//! parsed when the document is processed, except the email address, which is not
37//! parsed. [`metadata_schema`] describes the same form as a JSON Schema.
38
39use std::fmt;
40
41use serde_json::{Map, Value};
42
43use super::{DocMeta, MetaAuthor, MetaPlace, MetaText};
44
45/// The key of the title, `title`: one text.
46pub const TITLE_KEY: &str = "title";
47
48/// The key of the authors, `author`: one author, or a list of authors, each a text
49/// (the author's name) or a map (see the [module documentation](self)).
50pub const AUTHOR_KEY: &str = "author";
51
52/// The key of the date, `date`: one text, as the author writes the date.
53pub const DATE_KEY: &str = "date";
54
55/// The key of an author's name in an author's map, `name`: one text, required.
56pub const NAME_KEY: &str = "name";
57
58/// The key of an author's affiliations in an author's map, `affiliation`: one text,
59/// or a list of texts.
60pub const AFFILIATION_KEY: &str = "affiliation";
61
62/// The key of an author's email address in an author's map, `email`: one text, a
63/// plain address.
64pub const EMAIL_KEY: &str = "email";
65
66/// The key of the notes about an author in an author's map, `note`: one text, or a
67/// list of texts.
68pub const NOTE_KEY: &str = "note";
69
70/// Returns the JSON Schema of the metadata written as data, in the form the
71/// [module documentation](self) states: a map in which [`TITLE_KEY`] and
72/// [`DATE_KEY`] hold texts, [`AUTHOR_KEY`] one author or a list of authors, and any
73/// other key any value. The schema refers to no definition of its own. A program
74/// uses it to describe the files in which authors write metadata, for example to
75/// an editor that checks them.
76pub fn metadata_schema() -> Value {
77    let text = || serde_json::json!({ "type": ["string", "number", "boolean"] });
78    let texts = |description: &str| {
79        serde_json::json!({
80            "description": description,
81            "anyOf": [text(), { "type": "array", "items": text() }],
82        })
83    };
84    let entry = serde_json::json!({
85        "anyOf": [
86            text(),
87            {
88                "type": "object",
89                "properties": {
90                    NAME_KEY: {
91                        "description": "The author's name, a text in FLM.",
92                        "type": ["string", "number", "boolean"],
93                    },
94                    AFFILIATION_KEY: texts("The author's affiliations: one text in FLM, or a list of texts."),
95                    EMAIL_KEY: {
96                        "description": "The author's email address, a plain text, not FLM.",
97                        "type": ["string", "number", "boolean"],
98                    },
99                    NOTE_KEY: texts("The notes about the author: one text in FLM, or a list of texts."),
100                },
101                "required": [NAME_KEY],
102            },
103        ],
104    });
105    serde_json::json!({
106        "type": "object",
107        "description": "The metadata of the document: its title, its authors, its date, and any other key, \
108            whose value is kept as written.",
109        "properties": {
110            TITLE_KEY: {
111                "description": "The title of the document, a text in FLM.",
112                "type": ["string", "number", "boolean"],
113            },
114            AUTHOR_KEY: {
115                "description": "The authors of the document: one author, or a list of authors. An author is \
116                    a text in FLM, the author's name, or a map with the author's `name` and, as the author \
117                    wishes, `affiliation`, `email` and `note`.",
118                "anyOf": [entry.clone(), { "type": "array", "items": entry }],
119            },
120            DATE_KEY: {
121                "description": "The date of the document, a text in FLM, as the author writes it.",
122                "type": ["string", "number", "boolean"],
123            },
124        },
125    })
126}
127
128/// Where a value is in the metadata's data: its key, then the steps from the key's
129/// value down to the value ([`MetaStep`]). It is displayed as the key and the steps
130/// joined by `.`: `author.1` for the second author of a list, `author.0.affiliation`
131/// for the affiliations of the first, and the key alone for the key's own value.
132#[derive(Debug, Clone, PartialEq, Eq, Hash)]
133pub struct MetaPath {
134    /// The key.
135    pub key: String,
136    /// The steps from the key's value down to the value, outermost first; none for
137    /// the key's own value.
138    pub steps: Vec<MetaStep>,
139}
140
141impl MetaPath {
142    /// Returns the path of the value of `key`.
143    pub fn of(key: impl Into<String>) -> MetaPath {
144        MetaPath { key: key.into(), steps: Vec::new() }
145    }
146
147    /// Returns the path one step further down, at `step`.
148    pub fn then(&self, step: MetaStep) -> MetaPath {
149        let mut path = self.clone();
150        path.steps.push(step);
151        path
152    }
153}
154
155/// One step of a [`MetaPath`] into a value: an item of a list, or the value of a
156/// key of a map.
157#[derive(Debug, Clone, PartialEq, Eq, Hash)]
158pub enum MetaStep {
159    /// The item at this position in a list, counted from 0.
160    Index(usize),
161    /// The value of this key in a map.
162    Key(String),
163}
164
165impl fmt::Display for MetaPath {
166    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167        f.write_str(&self.key)?;
168        for step in &self.steps {
169            match step {
170                MetaStep::Index(index) => write!(f, ".{index}")?,
171                MetaStep::Key(key) => write!(f, ".{key}")?,
172            }
173        }
174        Ok(())
175    }
176}
177
178/// A value of the metadata's data that is not of the form the [module
179/// documentation](self) states: where it is, and what is wrong. It is displayed
180/// as its [`detail`](MetaDataError::detail).
181#[derive(Debug, Clone, PartialEq, Eq)]
182pub struct MetaDataError {
183    /// The value at fault: for a missing key, the map that lacks it.
184    pub path: MetaPath,
185    /// The problem, as a sentence for a person to read.
186    pub detail: String,
187}
188
189impl fmt::Display for MetaDataError {
190    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191        f.write_str(&self.detail)
192    }
193}
194
195impl std::error::Error for MetaDataError {}
196
197impl DocMeta {
198    /// Returns the metadata written as `data`, a map from a key to its value, in
199    /// the form the [module documentation](self) states.
200    ///
201    /// `place_of` returns where each value is written, when the caller knows it;
202    /// each text then carries its place, so that a problem in it is reported
203    /// there.
204    ///
205    /// # Errors
206    ///
207    /// A [`MetaDataError`], with its path, for each value of `title`, `author` and
208    /// `date`, or inside `author`, that is not of the form stated. An author's map
209    /// whose `name` is missing or is not a text gives one error, and its other keys
210    /// are not read: an error in its `affiliation`, `email` or `note` is reported
211    /// only once its `name` is a text.
212    ///
213    /// # Examples
214    ///
215    /// ```
216    /// use flm_core::stdlib::features::metadata::{DocMeta, MetaPlace};
217    ///
218    /// let data = serde_json::json!({
219    ///     "title": "On \\emph{flexible} markup",
220    ///     "author": [{"name": "Ada", "affiliation": "University of X"}, "Grace"],
221    ///     "date": 2026,
222    ///     "keywords": ["markup"],
223    /// });
224    /// let meta = DocMeta::from_data(data.as_object().unwrap(), |path| {
225    ///     Some(MetaPlace::new("paper.flm", if path.key == "title" { 2 } else { 3 }, 8))
226    /// })
227    /// .unwrap();
228    /// assert_eq!(meta.title.unwrap().place.unwrap().line, 2);
229    /// assert_eq!(meta.authors.len(), 2);
230    /// assert_eq!(meta.authors[0].affiliations[0].text, "University of X");
231    /// assert_eq!(meta.date.unwrap().text, "2026");
232    /// assert!(meta.other.contains_key("keywords"));
233    /// ```
234    pub fn from_data(
235        data: &Map<String, Value>,
236        place_of: impl Fn(&MetaPath) -> Option<MetaPlace>,
237    ) -> Result<DocMeta, Vec<MetaDataError>> {
238        let reader = Reader { place_of: &place_of };
239        let mut meta = DocMeta::default();
240        let mut errors = Vec::new();
241        for (key, value) in data {
242            let path = MetaPath::of(key.as_str());
243            match key.as_str() {
244                TITLE_KEY => meta.title = reader.text(&path, value, &mut errors),
245                DATE_KEY => meta.date = reader.text(&path, value, &mut errors),
246                AUTHOR_KEY => meta.authors = reader.authors(&path, value, &mut errors),
247                _ => {
248                    meta.other.insert(key.clone(), value.clone());
249                }
250            }
251        }
252        if errors.is_empty() { Ok(meta) } else { Err(errors) }
253    }
254}
255
256/// Reads the values of the metadata's data, each text with its place, and collects
257/// the errors.
258struct Reader<'p> {
259    place_of: &'p dyn Fn(&MetaPath) -> Option<MetaPlace>,
260}
261
262impl Reader<'_> {
263    /// Returns the text `value` at `path`: a text, or a number or a truth value
264    /// read as the text it is written as; `None`, with the error, for a value of
265    /// another shape.
266    fn text(&self, path: &MetaPath, value: &Value, errors: &mut Vec<MetaDataError>) -> Option<MetaText> {
267        let text = match value {
268            Value::String(text) => text.clone(),
269            Value::Number(number) => number.to_string(),
270            Value::Bool(value) => value.to_string(),
271            _ => {
272                errors.push(MetaDataError {
273                    path: path.clone(),
274                    detail: format!("‘{path}’ must be a text, a number or a truth value"),
275                });
276                return None;
277            }
278        };
279        let text = MetaText::new(text);
280        Some(match (self.place_of)(path) {
281            Some(place) => text.at(place),
282            None => text,
283        })
284    }
285
286    /// Returns the texts of `value` at `path`: one text, or a list of texts.
287    fn texts(&self, path: &MetaPath, value: &Value, errors: &mut Vec<MetaDataError>) -> Vec<MetaText> {
288        match value {
289            Value::Array(items) => items
290                .iter()
291                .enumerate()
292                .filter_map(|(index, item)| self.text(&path.then(MetaStep::Index(index)), item, errors))
293                .collect(),
294            Value::Object(_) | Value::Null => {
295                errors.push(MetaDataError {
296                    path: path.clone(),
297                    detail: format!("‘{path}’ must be a text or a list of texts"),
298                });
299                Vec::new()
300            }
301            _ => self.text(path, value, errors).into_iter().collect(),
302        }
303    }
304
305    /// Returns the authors of `value`, the value of `author`: one author, or a list
306    /// of authors.
307    fn authors(&self, path: &MetaPath, value: &Value, errors: &mut Vec<MetaDataError>) -> Vec<MetaAuthor> {
308        match value {
309            Value::Array(items) => items
310                .iter()
311                .enumerate()
312                .filter_map(|(index, item)| self.author(&path.then(MetaStep::Index(index)), item, errors))
313                .collect(),
314            Value::Null => {
315                errors.push(MetaDataError {
316                    path: path.clone(),
317                    detail: format!("‘{path}’ must be a name, a map with the key ‘{NAME_KEY}’, or a list of these"),
318                });
319                Vec::new()
320            }
321            _ => self.author(path, value, errors).into_iter().collect(),
322        }
323    }
324
325    /// Returns the author `value` at `path`: a text, the author's name, or a map
326    /// holding `name` and, as the author wishes, `affiliation`, `email`, `note` and
327    /// other keys.
328    fn author(&self, path: &MetaPath, value: &Value, errors: &mut Vec<MetaDataError>) -> Option<MetaAuthor> {
329        let entries = match value {
330            Value::Object(entries) => entries,
331            Value::Array(_) | Value::Null => {
332                errors.push(MetaDataError {
333                    path: path.clone(),
334                    detail: format!("‘{path}’ must be a name or a map with the key ‘{NAME_KEY}’"),
335                });
336                return None;
337            }
338            _ => return self.text(path, value, errors).map(MetaAuthor::new),
339        };
340        let at = |key: &str| path.then(MetaStep::Key(key.to_string()));
341        let Some(name) = entries.get(NAME_KEY) else {
342            errors.push(MetaDataError { path: path.clone(), detail: format!("Missing key ‘{NAME_KEY}’ in ‘{path}’") });
343            return None;
344        };
345        let mut author = MetaAuthor::new(self.text(&at(NAME_KEY), name, errors)?);
346        for (key, value) in entries {
347            match key.as_str() {
348                NAME_KEY => {}
349                AFFILIATION_KEY => author.affiliations = self.texts(&at(key), value, errors),
350                EMAIL_KEY => author.email = self.text(&at(key), value, errors),
351                NOTE_KEY => author.notes = self.texts(&at(key), value, errors),
352                _ => {
353                    author.other.insert(key.clone(), value.clone());
354                }
355            }
356        }
357        Some(author)
358    }
359}
360
361#[cfg(test)]
362mod tests {
363    use super::*;
364
365    fn read(data: Value) -> Result<DocMeta, Vec<MetaDataError>> {
366        DocMeta::from_data(data.as_object().unwrap(), |_| None)
367    }
368
369    #[test]
370    fn an_author_is_a_text_a_list_of_texts_or_a_list_with_maps() {
371        let meta = read(serde_json::json!({"author": "Ada", "date": 2026, "draft": true})).unwrap();
372        assert_eq!(meta.authors, [MetaAuthor::new(MetaText::new("Ada"))]);
373        assert_eq!(meta.date, Some(MetaText::new("2026")));
374        assert_eq!(meta.other["draft"], Value::Bool(true));
375        let meta = read(serde_json::json!({"author": ["Ada", "Grace"]})).unwrap();
376        assert_eq!(meta.authors.len(), 2);
377        let meta = read(serde_json::json!({"author": [
378            {"name": "Ada", "affiliation": ["U. of X", "I. of Y"], "email": "ada@example.com",
379             "note": "Corresponding author", "orcid": "0000"},
380            "Grace",
381        ]}))
382        .unwrap();
383        let ada = MetaAuthor::new(MetaText::new("Ada"))
384            .affiliation(MetaText::new("U. of X"))
385            .affiliation(MetaText::new("I. of Y"))
386            .email(MetaText::new("ada@example.com"))
387            .note(MetaText::new("Corresponding author"))
388            .other("orcid", serde_json::json!("0000"));
389        assert_eq!(meta.authors, [ada, MetaAuthor::new(MetaText::new("Grace"))]);
390    }
391
392    #[test]
393    fn a_value_of_another_shape_and_an_author_without_a_name_are_refused_at_their_paths() {
394        let errors = read(serde_json::json!({
395            "title": ["a"],
396            "author": ["Ada", {"x": 1}, {"name": "Grace", "affiliation": {"y": 2}}],
397        }))
398        .unwrap_err();
399        let paths: Vec<String> = errors.iter().map(|error| error.path.to_string()).collect();
400        assert_eq!(paths.len(), 3, "{paths:?}");
401        assert!(paths.contains(&String::from("title")));
402        assert!(paths.contains(&String::from("author.1")));
403        assert!(paths.contains(&String::from("author.2.affiliation")));
404    }
405}