Skip to main content

flm_core/core/
artifact.rs

1//! Artifacts: one file's worth of output held as a value, the artifact set
2//! that makes up one output, and the naming service a host supplies to turn
3//! an artifact's identity into a path.
4//!
5//! An artifact is one file's worth of output held as a value, identified by
6//! its producer and a name and never by a path: the bytes of a page, a
7//! stylesheet, a copied image; a *folder artifact* holds the files of a whole
8//! folder instead (see [A folder artifact](#a-folder-artifact) below). An
9//! artifact set is the artifacts of one output, at most one of which is the
10//! entry artifact, the one that represents the output as a whole (the HTML
11//! page, the text, the LaTeX document). An output is a name a caller asks
12//! for, such as `text` or `html`
13//! ([`OutputDef`]); the output's table holds
14//! its artifact set. A backend's final stage puts the set into that table,
15//! and the caller reads it from there. For the place of outputs in the
16//! processing of a document, see [backends, lowering, and
17//! outputs](crate::guide::concepts_overview#backends-lowering-and-outputs).
18//!
19//! The items of this module:
20//!
21//! - [`Artifact`], one artifact, and [`ArtifactData`], its content: the bytes,
22//!   a [`FileRef`] to a file that holds them, or the files of a folder;
23//! - [`ArtifactId`], an artifact's identity, and [`RelPath`], a relative path;
24//! - [`ArtifactSet`], the artifacts of one output, with
25//!   [`ArtifactSetViolation`] for the two ways a set can be malformed, and the
26//!   two conditions reported for them, [`DuplicateArtifact`] and
27//!   [`SecondEntryArtifact`];
28//! - [`ArtifactNamer`], the naming service that turns an identity into a
29//!   path, with its two inputs: [`ArtifactRef`], what is named, and
30//!   [`NamingScope`] ([`ScopedOutput`]), the outputs of the command;
31//! - [`path_of`], the path at which a host writes an artifact: its fixed path,
32//!   else the naming service's answer;
33//! - [`media_type_of`], the media type of a file by its extension.
34//!
35//! # Identity, not paths
36//!
37//! An artifact is identified by an [`ArtifactId`]: the feature or backend that
38//! contributed it, and a name that this producer chose. This library writes
39//! no file, so an artifact has no path of its own. A host that writes the
40//! artifacts out asks its [`ArtifactNamer`] for the path of each identity.
41//! Because the naming service computes the path from the identity and a few
42//! facts known in advance (the entry role, the media type, the extension, the
43//! outputs of the command), a producer can write a link to another artifact
44//! before that artifact's bytes exist. [`path_of`] states the whole rule: an
45//! artifact's [fixed path](Artifact::fixed_path) when it has one, else the
46//! naming service's answer.
47//!
48//! # A folder artifact
49//!
50//! An artifact whose data is [`ArtifactData::Files`] is a *folder artifact*:
51//! the files of one folder, each by its path relative to the folder, shipped
52//! together under one identity (a compose template's folder of icons, for
53//! instance). The naming service names the folder ([`ArtifactRef::folder`]);
54//! a host that writes it writes each file under that folder with its own
55//! path. A folder artifact has no extension and no media type of its own
56//! ([`Artifact::folder`]); each of its files takes the media type its own
57//! extension gives.
58//!
59//! # The entry artifact
60//!
61//! At most one artifact of a set is its **entry artifact**: the one that
62//! represents the output as a whole, such as the page a reader opens or the
63//! file a build system is given. A one-file output is a set of one artifact,
64//! which is the entry artifact. The registry records what is known about an
65//! output's entry artifact before anything is rendered, its media type and
66//! file extension, in [`OutputEntry`](crate::core::registry::OutputEntry).
67//!
68//! Artifacts enter a set in two ways, which treat a violation of the
69//! one-entry rule differently because only one of them can refuse.
70//! [`ArtifactSet::insert`] is what a producer calls; it returns a [`Result`]
71//! and refuses a second entry artifact or a repeated identity.
72//! [`Table::absorb`], which combines the table pieces that several stage
73//! invocations wrote, cannot fail (no table's `absorb` can), so it keeps the
74//! first artifact, turns a second entry artifact into an ordinary artifact,
75//! and records each violation in [`ArtifactSet::violations`].
76//!
77//! # The same artifact twice
78//!
79//! When table pieces are combined, an artifact equal in every field to one
80//! the set already holds (the same identity, content, media type, entry role,
81//! fixed path and links) is the same artifact contributed twice. It is
82//! dropped and nothing is recorded: when two trees of a document show one
83//! image, both contribute its copy, and the document is not at fault. Two
84//! artifacts that differ under one identity are a violation, as above.
85//!
86//! # Making an output's set, and reporting a malformed one
87//!
88//! The stage that finishes an output (the backend's [final
89//! stage](crate::guide::concepts_overview#output-regions-and-the-final-stage)
90//! or a host's template stage) makes its set with
91//! [`ArtifactSet::insert_entry_with`]: the entry artifact first, then the
92//! artifacts of the tables of files written beside it. That function returns
93//! one Error diagnostic for every violation the finished set holds
94//! ([`DuplicateArtifact`], [`SecondEntryArtifact`]), whichever of those stages
95//! calls it.
96
97use std::collections::{BTreeMap, BTreeSet};
98use std::fmt;
99
100use techy::error::{Diagnostic, DiagnosticInfo};
101use techy::serialize::SerialValue;
102
103use crate::core::data::table::{PieceClass, ProjectCx, Table};
104use crate::core::registry::{FlmRegistry, OutputDef};
105use crate::lang::origin::nowhere;
106use crate::lang::{FlmDiagnostic, FlmOrigin};
107use crate::model::digest::Fnv1a64;
108use crate::model::names::{CapName, Name, OutputName};
109
110/// A relative path, written with forward slashes and no leading slash.
111///
112/// An [`ArtifactNamer`] returns one for each artifact, and a producer may set
113/// one as an artifact's [`fixed_path`](Artifact::fixed_path). The path is
114/// relative to the place where the host writes the output; this library
115/// writes no file and gives the text no meaning beyond that form. The
116/// `graphics` feature, for example, writes the path the naming service
117/// returns for a copied image as the image's address, and the recomposed LaTeX
118/// sets the fixed path of its style file.
119#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
120pub struct RelPath(String);
121
122impl RelPath {
123    /// Returns a relative path holding `path` as written, unchecked.
124    pub fn new(path: impl Into<String>) -> RelPath {
125        RelPath(path.into())
126    }
127
128    /// Returns the path's text.
129    pub fn as_str(&self) -> &str {
130        &self.0
131    }
132}
133
134impl fmt::Display for RelPath {
135    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136        f.write_str(&self.0)
137    }
138}
139
140/// An artifact's identity: the feature or backend that contributed it, and a
141/// name that this producer chose.
142///
143/// The name is the producer's own (`document`, `style`, `fig-3`); this library
144/// never interprets it. A producer must choose the same name for the same
145/// artifact in every run, so that a link written in one artifact still points
146/// at the right one. Everything else refers to an artifact by its identity:
147/// an [`ArtifactSet`] is keyed by it, one artifact links to another through
148/// it ([`Artifact::refs`]), and an [`ArtifactNamer`] turns it into a path.
149///
150/// Its [`Display`](fmt::Display) form is `owner:name`.
151///
152/// # Examples
153///
154/// ```
155/// use flm_core::core::artifact::ArtifactId;
156///
157/// let id = ArtifactId::new("text", "document");
158/// assert_eq!(id.to_string(), "text:document");
159/// ```
160#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
161pub struct ArtifactId {
162    /// The name of the feature or backend that contributed the artifact.
163    pub owner: Name,
164    /// The name the producer chose, which no other artifact of that owner
165    /// has.
166    pub name: String,
167}
168
169impl ArtifactId {
170    /// Returns the identity of the artifact `name` contributed by `owner`.
171    pub fn new(owner: impl Into<Name>, name: impl Into<String>) -> ArtifactId {
172        ArtifactId { owner: owner.into(), name: name.into() }
173    }
174}
175
176impl fmt::Display for ArtifactId {
177    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178        write!(f, "{}:{}", self.owner, self.name)
179    }
180}
181
182/// Returns `text` with every character other than an ASCII letter, a digit, `-` and `_`
183/// written `_`, so that it can begin the name of an artifact, which the naming service
184/// writes into a path.
185pub(crate) fn name_safe(text: &str) -> String {
186    text.chars().map(|c| if c.is_ascii_alphanumeric() || matches!(c, '-' | '_') { c } else { '_' }).collect()
187}
188
189/// Returns the name of an artifact that its content names, `<stem>-<digest>`: `stem` as
190/// given, a hyphen, and eight hexadecimal digits of `digest`. The name has no counter, so
191/// that one content given twice is one artifact.
192pub(crate) fn digest_name(stem: &str, digest: &Fnv1a64) -> String {
193    format!("{stem}-{:08x}", digest.value() >> 32)
194}
195
196/// The location of a file holding an artifact's bytes, written the way the
197/// host that produced the file writes paths.
198///
199/// A file reference keeps a large artifact out of memory: a host that ran an
200/// external converter, or that keeps intermediate files in a working folder,
201/// passes on the location instead of the bytes. This library treats the text
202/// as opaque: it is not a [`RelPath`], and nothing in this library opens it.
203///
204/// No feature of this library produces a file reference: every artifact the
205/// standard backends make holds its bytes.
206#[derive(Debug, Clone, PartialEq, Eq, Hash)]
207pub struct FileRef {
208    /// Where the file is, as the host that produced it spells it.
209    pub location: String,
210}
211
212/// An artifact's content: the bytes themselves, a reference to a file
213/// holding them, or the files of a folder.
214///
215/// [`Artifact::as_bytes`] returns the bytes in the first case and `None` in
216/// the other two.
217#[derive(Clone, PartialEq, Eq, Hash)]
218pub enum ArtifactData {
219    /// The bytes, in memory.
220    Bytes(Vec<u8>),
221    /// A [`FileRef`] to a file holding the bytes, for an artifact too large to
222    /// hold in memory.
223    FileRef(FileRef),
224    /// The files of a folder artifact (see the [module
225    /// documentation](self#a-folder-artifact)), each by its path relative to
226    /// the folder and its bytes, in the order the producer gives. Each path is
227    /// relative, written with forward slashes, and no two are equal; the host
228    /// places each file at its path with `.` and `..` resolved as text, and
229    /// refuses a path that leaves the output folder.
230    Files(Vec<(RelPath, Vec<u8>)>),
231}
232
233impl fmt::Debug for ArtifactData {
234    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
235        match self {
236            ArtifactData::Bytes(bytes) => write!(f, "Bytes({} bytes)", bytes.len()),
237            ArtifactData::FileRef(file) => write!(f, "FileRef({:?})", file.location),
238            ArtifactData::Files(files) => {
239                let paths: Vec<&str> = files.iter().map(|(path, _)| path.as_str()).collect();
240                write!(f, "Files({paths:?})")
241            }
242        }
243    }
244}
245
246/// One file's worth of output held as a value: an identity, a media type, the
247/// content, and whether it is the entry artifact of its set. A folder artifact
248/// ([`Artifact::folder`]) holds the files of a folder as its content.
249///
250/// A stage builds an artifact with [`Artifact::bytes`] and puts it into an
251/// [`ArtifactSet`]. This library writes nothing to disk; the host decides
252/// whether and where the bytes become a file (see the [module
253/// documentation](self)).
254///
255/// # Examples
256///
257/// ```
258/// use flm_core::core::artifact::{Artifact, ArtifactId};
259///
260/// let artifact = Artifact::bytes(
261///     ArtifactId::new("text", "document"),
262///     "text/plain",
263///     b"Hello.".to_vec(),
264/// )
265/// .as_entry();
266///
267/// assert!(artifact.entry);
268/// assert_eq!(artifact.as_bytes(), Some(&b"Hello."[..]));
269/// ```
270#[derive(Debug, Clone, PartialEq, Eq)]
271pub struct Artifact {
272    /// The artifact's identity.
273    pub id: ArtifactId,
274    /// Whether this artifact is the entry artifact of the set it belongs to
275    /// (see the [module documentation](self#the-entry-artifact)).
276    pub entry: bool,
277    /// The media type, such as `text/plain` or `text/html`; the empty text for
278    /// a folder artifact, whose files each take the media type of their own
279    /// extension.
280    pub media_type: String,
281    /// The bytes, a reference to the file holding them, or the files of a
282    /// folder artifact.
283    pub data: ArtifactData,
284    /// A path the producer requires for this artifact. A host that writes the
285    /// artifact uses this path as given instead of asking its
286    /// [`ArtifactNamer`]. The recomposed LaTeX sets it on its style file,
287    /// whose file name the LaTeX document refers to.
288    pub fixed_path: Option<RelPath>,
289    /// The other artifacts this artifact's bytes link to. The HTML and
290    /// recomposed LaTeX final stages set it on the entry artifact from the
291    /// [`Regions::refs`](crate::core::region::Regions::refs) of their output.
292    pub refs: Vec<ArtifactId>,
293    /// The file extension the producer gives, without the dot (`sty`, `png`);
294    /// `None` leaves it to the host's table over media types. A host that
295    /// writes the artifact passes it to its [`ArtifactNamer`]
296    /// ([`ArtifactRef::extension`]). Set it with [`Artifact::with_extension`].
297    /// It is `None` for a folder artifact, whose path has no extension.
298    pub extension: Option<String>,
299}
300
301impl Artifact {
302    /// Returns an artifact of identity `id` and media type `media_type`
303    /// holding `bytes`: not the entry artifact, with no fixed path, no links
304    /// and no extension of its own.
305    ///
306    /// Mark it as the entry artifact with [`Artifact::as_entry`].
307    pub fn bytes(id: ArtifactId, media_type: impl Into<String>, bytes: Vec<u8>) -> Artifact {
308        Artifact {
309            id,
310            entry: false,
311            media_type: media_type.into(),
312            data: ArtifactData::Bytes(bytes),
313            fixed_path: None,
314            refs: Vec::new(),
315            extension: None,
316        }
317    }
318
319    /// Returns the folder artifact of identity `id` holding `files`, each by
320    /// its path relative to the folder ([`ArtifactData::Files`]): not the
321    /// entry artifact, with no fixed path, no links, no extension and the
322    /// empty text as its media type (see the [module
323    /// documentation](self#a-folder-artifact)).
324    ///
325    /// # Examples
326    ///
327    /// ```
328    /// use flm_core::core::artifact::{Artifact, ArtifactData, ArtifactId, RelPath};
329    ///
330    /// let icons = Artifact::folder(
331    ///     ArtifactId::new("compose", "icons"),
332    ///     vec![(RelPath::new("check.svg"), b"<svg/>".to_vec())],
333    /// );
334    /// assert!(matches!(icons.data, ArtifactData::Files(_)));
335    /// assert_eq!((icons.media_type.as_str(), icons.extension), ("", None));
336    /// ```
337    pub fn folder(id: ArtifactId, files: Vec<(RelPath, Vec<u8>)>) -> Artifact {
338        Artifact {
339            id,
340            entry: false,
341            media_type: String::new(),
342            data: ArtifactData::Files(files),
343            fixed_path: None,
344            refs: Vec::new(),
345            extension: None,
346        }
347    }
348
349    /// Sets the artifact's file extension to `extension`, written without the
350    /// dot (`sty`), and returns it. See [`Artifact::extension`].
351    pub fn with_extension(mut self, extension: impl Into<String>) -> Artifact {
352        self.extension = Some(extension.into());
353        self
354    }
355
356    /// Marks the artifact as the entry artifact of its set, and returns it.
357    ///
358    /// A set holds at most one entry artifact; see the [module
359    /// documentation](self#the-entry-artifact) for what happens to a second
360    /// one.
361    pub fn as_entry(mut self) -> Artifact {
362        self.entry = true;
363        self
364    }
365
366    /// Returns the bytes, or `None` when the content is a [`FileRef`] or the
367    /// files of a folder.
368    pub fn as_bytes(&self) -> Option<&[u8]> {
369        match &self.data {
370            ArtifactData::Bytes(bytes) => Some(bytes),
371            ArtifactData::FileRef(_) | ArtifactData::Files(_) => None,
372        }
373    }
374}
375
376/// One of the two ways an [`ArtifactSet`] can be malformed: two artifacts with
377/// one identity, or two entry artifacts.
378///
379/// [`ArtifactSet::insert`] returns this error instead of adding the artifact.
380/// [`Table::absorb`] cannot refuse anything, so it repairs the set as
381/// described on each variant and records the violation in
382/// [`ArtifactSet::violations`]; [`ArtifactSet::insert_entry_with`] then reports
383/// each recorded violation as an Error diagnostic.
384#[derive(Debug, Clone, PartialEq, Eq)]
385pub enum ArtifactSetViolation {
386    /// Two artifacts have the same identity. The artifact already in the set
387    /// is kept and the later one is dropped.
388    DuplicateId(ArtifactId),
389    /// A second artifact is marked as the entry artifact. The first keeps that
390    /// role, and the second is kept as an ordinary artifact.
391    SecondEntry {
392        /// The artifact that stays the entry artifact.
393        first: ArtifactId,
394        /// The artifact refused the role of entry artifact.
395        second: ArtifactId,
396    },
397}
398
399impl fmt::Display for ArtifactSetViolation {
400    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
401        match self {
402            ArtifactSetViolation::DuplicateId(id) => {
403                write!(f, "two different files of an output must not share the identity `{id}`")
404            }
405            ArtifactSetViolation::SecondEntry { first, second } => write!(
406                f,
407                "an output has only one main file, `{first}`, so `{second}` must not also be \
408                 marked as the main file"
409            ),
410        }
411    }
412}
413
414impl std::error::Error for ArtifactSetViolation {}
415
416/// An artifact set: the artifacts of one output, at most one of which is the
417/// entry artifact, the one that represents the output as a whole.
418///
419/// This is the value an output's table holds
420/// ([`OutputDef`]), so producing an output
421/// means writing one of these; see the [module documentation](self). The set
422/// keeps its artifacts in identity order, the order of [`ArtifactSet::iter`].
423///
424/// It is a [`Table`]: a stage that runs once per tree may write one table
425/// piece per tree, and the runner combines them ([`Table::absorb`]). The
426/// standard backends' final stages run once for the whole document and make
427/// the finished set with [`ArtifactSet::insert_entry_with`].
428///
429/// # Examples
430///
431/// ```
432/// use flm_core::core::artifact::{Artifact, ArtifactId, ArtifactSet, ArtifactSetViolation};
433///
434/// let page = |name: &str| {
435///     Artifact::bytes(ArtifactId::new("html", name), "text/html", b"<p>x</p>".to_vec())
436/// };
437///
438/// let mut set = ArtifactSet::new();
439/// set.insert(page("index").as_entry()).unwrap();
440/// set.insert(page("chapter-1")).unwrap();
441///
442/// assert_eq!(set.len(), 2);
443/// assert_eq!(set.entry().map(|a| a.id.name.as_str()), Some("index"));
444///
445/// // A second entry is refused, and the set is left as it was.
446/// let refused = set.insert(page("chapter-2").as_entry()).unwrap_err();
447/// assert!(matches!(refused, ArtifactSetViolation::SecondEntry { .. }));
448/// assert_eq!(set.len(), 2);
449/// ```
450#[derive(Debug, Clone, Default)]
451pub struct ArtifactSet {
452    artifacts: BTreeMap<ArtifactId, Artifact>,
453    entry: Option<ArtifactId>,
454    violations: Vec<ArtifactSetViolation>,
455}
456
457impl ArtifactSet {
458    /// Returns an empty set: no artifact and no entry artifact.
459    pub fn new() -> ArtifactSet {
460        ArtifactSet::default()
461    }
462
463    /// Adds `artifact` to the set.
464    ///
465    /// # Errors
466    ///
467    /// Returns [`ArtifactSetViolation::DuplicateId`] when the set already
468    /// holds an artifact of that identity, even an equal one, and
469    /// [`ArtifactSetViolation::SecondEntry`] when the artifact is marked as
470    /// the entry artifact and the set already has one. In both cases the set
471    /// is left unchanged.
472    pub fn insert(&mut self, artifact: Artifact) -> Result<(), ArtifactSetViolation> {
473        if self.artifacts.contains_key(&artifact.id) {
474            return Err(ArtifactSetViolation::DuplicateId(artifact.id));
475        }
476        if artifact.entry {
477            if let Some(first) = &self.entry {
478                return Err(ArtifactSetViolation::SecondEntry {
479                    first: first.clone(),
480                    second: artifact.id,
481                });
482            }
483            self.entry = Some(artifact.id.clone());
484        }
485        self.artifacts.insert(artifact.id.clone(), artifact);
486        Ok(())
487    }
488
489    /// Adds an output's entry artifact `entry`, then every artifact of each
490    /// set in `beside`, in order (the files the output's stages write for the
491    /// entry artifact to link to), and returns one Error diagnostic for every
492    /// violation the set then holds.
493    ///
494    /// The stage that finishes an output (the backend's final stage or a
495    /// host's template stage) makes its set with this function. The artifacts of `beside` are combined as [`Table::absorb`]
496    /// combines table pieces: an artifact equal to one already in the set is
497    /// dropped, and a repeated identity or a second entry artifact is recorded
498    /// among the set's [violations](ArtifactSet::violations). Every recorded
499    /// violation, including those the sets of `beside` already held, is then
500    /// returned as one Error diagnostic ([`DuplicateArtifact`],
501    /// [`SecondEntryArtifact`]), which the caller adds to its stage's
502    /// diagnostics. See the [module
503    /// documentation](self#making-an-outputs-set-and-reporting-a-malformed-one).
504    ///
505    /// # Errors
506    ///
507    /// Returns the violation of [`ArtifactSet::insert`] when `entry` itself
508    /// cannot be added; nothing of `beside` is added then.
509    #[must_use = "the returned Error diagnostics report the violations of the artifact set; \
510                  the caller must add them to its diagnostics"]
511    pub fn insert_entry_with(
512        &mut self,
513        entry: Artifact,
514        beside: &[&ArtifactSet],
515    ) -> Result<Vec<FlmDiagnostic>, ArtifactSetViolation> {
516        self.insert(entry)?;
517        for set in beside {
518            self.absorb((*set).clone());
519        }
520        let mut reports = Vec::new();
521        for violation in &self.violations {
522            let at = nowhere(FlmOrigin::synthetic(REPORT_LABEL));
523            reports.push(match violation {
524                ArtifactSetViolation::DuplicateId(id) => {
525                    Diagnostic::error(DuplicateArtifact { id: id.to_string() }, at)
526                }
527                ArtifactSetViolation::SecondEntry { first, second } => Diagnostic::error(
528                    SecondEntryArtifact { first: first.to_string(), second: second.to_string() },
529                    at,
530                ),
531            });
532        }
533        Ok(reports)
534    }
535
536    /// Returns the entry artifact, or `None` when no artifact of the set is
537    /// marked as the entry artifact.
538    pub fn entry(&self) -> Option<&Artifact> {
539        self.entry.as_ref().and_then(|id| self.artifacts.get(id))
540    }
541
542    /// Returns the artifact of identity `id`, or `None` when the set holds
543    /// none.
544    pub fn get(&self, id: &ArtifactId) -> Option<&Artifact> {
545        self.artifacts.get(id)
546    }
547
548    /// Returns every artifact of the set, in identity order.
549    pub fn iter(&self) -> impl Iterator<Item = &Artifact> + '_ {
550        self.artifacts.values()
551    }
552
553    /// Returns the number of artifacts in the set.
554    pub fn len(&self) -> usize {
555        self.artifacts.len()
556    }
557
558    /// Returns whether the set holds no artifact.
559    pub fn is_empty(&self) -> bool {
560        self.artifacts.is_empty()
561    }
562
563    /// Returns the violations recorded while table pieces of this set were
564    /// combined, in the order they were found.
565    ///
566    /// [`ArtifactSet::insert_entry_with`] reports each one as an Error
567    /// diagnostic; see [`ArtifactSetViolation`]. An artifact refused by
568    /// [`ArtifactSet::insert`] is not recorded here, since that call returned
569    /// the violation to its caller.
570    pub fn violations(&self) -> &[ArtifactSetViolation] {
571        &self.violations
572    }
573}
574
575impl Table for ArtifactSet {
576    /// Combines the table piece `piece` into this set, keeping the violations
577    /// the table piece had already recorded.
578    ///
579    /// An artifact equal in every field to one the set holds is dropped, and
580    /// nothing is recorded: it is the same artifact contributed twice.
581    /// Otherwise a second entry artifact becomes an ordinary artifact, and an
582    /// artifact with a repeated identity is dropped; either way the violation
583    /// is recorded in [`ArtifactSet::violations`], because this operation
584    /// cannot fail.
585    fn absorb(&mut self, piece: ArtifactSet) {
586        self.violations.extend(piece.violations);
587        for (_, mut artifact) in piece.artifacts {
588            if self.artifacts.get(&artifact.id) == Some(&artifact) {
589                continue;
590            }
591            if artifact.entry {
592                if let Some(first) = &self.entry {
593                    self.violations.push(ArtifactSetViolation::SecondEntry {
594                        first: first.clone(),
595                        second: artifact.id.clone(),
596                    });
597                    artifact.entry = false;
598                }
599            }
600            if let Err(violation) = self.insert(artifact) {
601                self.violations.push(violation);
602            }
603        }
604    }
605
606    fn project(&self, _cx: &dyn ProjectCx) -> SerialValue {
607        let artifacts = self
608            .artifacts
609            .values()
610            .map(|artifact| {
611                SerialValue::Map(vec![
612                    ("id".to_string(), SerialValue::Str(artifact.id.to_string())),
613                    ("entry".to_string(), SerialValue::Bool(artifact.entry)),
614                    ("media_type".to_string(), SerialValue::Str(artifact.media_type.clone())),
615                    (
616                        "data".to_string(),
617                        match &artifact.data {
618                            ArtifactData::Bytes(bytes) => SerialValue::Bytes(bytes.clone()),
619                            ArtifactData::FileRef(file) => SerialValue::Str(file.location.clone()),
620                            ArtifactData::Files(files) => SerialValue::Map(
621                                files
622                                    .iter()
623                                    .map(|(path, bytes)| (path.to_string(), SerialValue::Bytes(bytes.clone())))
624                                    .collect(),
625                            ),
626                        },
627                    ),
628                ])
629            })
630            .collect();
631        SerialValue::Map(vec![
632            ("artifacts".to_string(), SerialValue::List(artifacts)),
633            (
634                "violations".to_string(),
635                SerialValue::List(
636                    self.violations.iter().map(|v| SerialValue::Str(v.to_string())).collect(),
637                ),
638            ),
639        ])
640    }
641
642    fn piece_class(&self) -> PieceClass {
643        if self.is_empty() { PieceClass::Empty } else { PieceClass::DocumentFact }
644    }
645}
646
647/// The label of the source at which the reports of a malformed set are
648/// located: they concern the files of an output, which have no place in the
649/// document.
650const REPORT_LABEL: &str = "the files of the output";
651
652/// Condition `flm.artifacts.duplicate`, an Error: two different files of an
653/// output were given one identity, so one of them is missing from the output
654/// ([`ArtifactSetViolation::DuplicateId`]).
655///
656/// [`ArtifactSet::insert_entry_with`] reports it. Recovery: the first file is
657/// kept.
658#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
659#[diagnostic(
660    id = "flm.artifacts.duplicate",
661    message = "two different files of the output must not share the identity `{id}`"
662)]
663pub struct DuplicateArtifact {
664    /// The shared identity, `owner:name`.
665    pub id: String,
666}
667
668/// Condition `flm.artifacts.second-entry`, an Error: two files of an output
669/// are both marked as the entry artifact, the file that represents the whole
670/// output ([`ArtifactSetViolation::SecondEntry`]).
671///
672/// [`ArtifactSet::insert_entry_with`] reports it. Recovery: the first file
673/// keeps that role, and the second is kept as an ordinary file.
674#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
675#[diagnostic(
676    id = "flm.artifacts.second-entry",
677    message = "an output has only one main file, `{first}`, so `{second}` must not also be \
678               marked as the main file"
679)]
680pub struct SecondEntryArtifact {
681    /// The identity of the file that stays the main file, `owner:name`.
682    pub first: String,
683    /// The identity of the file refused that role, `owner:name`.
684    pub second: String,
685}
686
687/// What an [`ArtifactNamer`] is asked to name: an artifact's identity and the
688/// facts about it that are known before its bytes are made.
689///
690/// A host's write stage builds one from each [`Artifact`] it places; a
691/// producer that needs the path of its own artifact during the run (the
692/// `graphics` feature's copy of an image, the recomposed LaTeX's style file, a
693/// compose template's own files) builds one from what it is about to make.
694#[derive(Debug, Clone, Copy, PartialEq, Eq)]
695pub struct ArtifactRef<'a> {
696    /// The artifact's identity.
697    pub id: &'a ArtifactId,
698    /// Whether the artifact is its output's entry artifact.
699    pub entry: bool,
700    /// The artifact's media type, such as `text/html`.
701    pub media_type: &'a str,
702    /// The file extension the producer gives (without the dot), when it gives
703    /// one; the namer derives one from the media type otherwise.
704    pub extension: Option<&'a str>,
705    /// The output the artifact is placed under, when the caller knows it: the
706    /// host's write stage does; a producer naming its own artifact during the
707    /// run gives `None`.
708    pub output: Option<&'a str>,
709    /// Whether the artifact is a folder artifact ([`ArtifactData::Files`]; see
710    /// the [module documentation](self#a-folder-artifact)). The namer then
711    /// names a folder: a path with no extension (and no trailing slash), under
712    /// which the host writes each of the folder's files with its own path.
713    /// [`extension`](ArtifactRef::extension) is `None` and
714    /// [`media_type`](ArtifactRef::media_type) the empty text for a folder.
715    pub folder: bool,
716}
717
718/// One output of a [`NamingScope`]: its name and the file extension of its
719/// entry artifact.
720#[derive(Debug, Clone, PartialEq, Eq)]
721pub struct ScopedOutput {
722    /// The output's name, such as `html`.
723    pub name: OutputName,
724    /// The file extension of the output's entry artifact, without the dot, as
725    /// the registry declares it
726    /// ([`OutputEntry::extension`](crate::core::registry::OutputEntry::extension)).
727    pub extension: String,
728}
729
730/// The outputs a command produces: what the paths of its files may depend on.
731///
732/// An [`ArtifactNamer`] receives it at every call, so that a path can depend on
733/// the outputs of the command (for instance on their extensions) while the
734/// namer stays a function of its arguments: the namer is contributed when the
735/// registry is built, and the outputs of a command are known only once a plan
736/// is made. Every caller of one run builds it the same way,
737/// [`NamingScope::of`] over the registry and the plan's demands, so it is the
738/// same for every call of the run.
739///
740/// # Examples
741///
742/// ```
743/// use flm_core::core::artifact::{NamingScope, ScopedOutput};
744///
745/// let scope = NamingScope {
746///     outputs: vec![ScopedOutput { name: "html".into(), extension: "html".to_string() }],
747/// };
748/// assert_eq!(scope.outputs[0].extension, "html");
749/// ```
750#[derive(Debug, Clone, Default, PartialEq, Eq)]
751pub struct NamingScope {
752    /// Each output's name and the file extension of its entry artifact, in the
753    /// registry's order.
754    pub outputs: Vec<ScopedOutput>,
755}
756
757impl NamingScope {
758    /// Returns the outputs of `registry` whose capability is among `demands`
759    /// (a plan's demands, [`Plan::demands`](crate::core::plan::Plan::demands)),
760    /// each with the extension of its entry artifact, in the registry's order.
761    /// Nothing demanded gives an empty scope.
762    pub fn of(registry: &FlmRegistry, demands: &BTreeSet<CapName>) -> NamingScope {
763        NamingScope {
764            outputs: registry
765                .outputs()
766                .filter(|output| demands.contains(&output.def.capability))
767                .map(|output| ScopedOutput {
768                    name: output.def.name.clone(),
769                    extension: output.def.entry.extension.clone(),
770                })
771                .collect(),
772        }
773    }
774}
775
776/// The naming service: the service a host supplies to decide where each
777/// artifact is written, as a function from what an artifact is
778/// ([`ArtifactRef`]) and the outputs of the command ([`NamingScope`]) to a
779/// relative path.
780///
781/// The path must depend only on the arguments and on the namer's own
782/// configuration, never on which artifacts exist or on how far a run has
783/// progressed, so that a producer can write a link to an artifact before that
784/// artifact's bytes are made. The scope is the same for every call of one run
785/// ([`NamingScope::of`] over the registry and the plan's demands), so a
786/// producer and the host's write stage get the same path for one artifact. A
787/// host that writes files uses the namer to turn the artifacts of an
788/// [`ArtifactSet`] into paths, except for an artifact that has a
789/// [`fixed_path`](Artifact::fixed_path). A stage may also call it while a run
790/// is under way: the `graphics` feature's publish stage computes the address
791/// of a copied image this way, the recomposed LaTeX names its style file, and
792/// a compose template's composer names the files the template ships.
793///
794/// This library ships no implementation. A host contributes its naming scheme
795/// to the service slot `flm.artifacts.namer`
796/// ([`NAMER_SLOT`](crate::stdlib::backends::lowering::NAMER_SLOT)), which the
797/// standard `lowering` feature declares; see [`crate::core::services`] for
798/// service slots. When no host contributes a namer, the slot is empty, and a
799/// stage that needs the path of an artifact cannot obtain one.
800pub trait ArtifactNamer: Send + Sync {
801    /// Returns the relative path at which the artifact `artifact` is written,
802    /// for a command producing the outputs of `scope`. For a folder artifact
803    /// ([`ArtifactRef::folder`]), it is the path of the folder, with no
804    /// extension and no trailing slash.
805    fn url_of(&self, artifact: &ArtifactRef<'_>, scope: &NamingScope) -> RelPath;
806}
807
808/// Returns the path at which a host writes the artifact `artifact`, relative to the place
809/// where it writes the output: the artifact's [`fixed_path`](Artifact::fixed_path) when it
810/// has one, else the path that the naming service `namer` gives it for a command producing
811/// the outputs of `scope`.
812///
813/// `output` is the declaration of the output whose artifact set holds the artifact, when
814/// the caller knows it. The namer then receives the output's name
815/// ([`ArtifactRef::output`]), and an entry artifact is named with the file extension that
816/// the output declares for its entry artifact
817/// ([`OutputEntry::extension`](crate::core::registry::OutputEntry::extension)), whatever
818/// extension the artifact gives itself. Every other artifact, and an entry artifact when
819/// `output` is `None`, is named with the extension it gives ([`Artifact::extension`]). A
820/// folder artifact is named as a folder ([`ArtifactRef::folder`]); each of its files is
821/// written under that path with its own path within the folder.
822///
823/// This is the one statement of where a file of an output is written: a host's write stage
824/// places each artifact with it, and a stage that hands the files of an output to another
825/// program asks it for the path each file must have so that the links between the files
826/// hold. Both build `scope` with [`NamingScope::of`] over the registry and the plan's
827/// demands, so they obtain the same path.
828///
829/// # Examples
830///
831/// ```
832/// use flm_core::core::artifact::{
833///     path_of, Artifact, ArtifactId, ArtifactNamer, ArtifactRef, NamingScope, RelPath,
834/// };
835/// use flm_core::core::registry::OutputDef;
836///
837/// /// Names an entry artifact `paper.EXT` and any other `paper-NAME.EXT`.
838/// struct Paper;
839/// impl ArtifactNamer for Paper {
840///     fn url_of(&self, artifact: &ArtifactRef<'_>, _: &NamingScope) -> RelPath {
841///         let extension = artifact.extension.unwrap_or("bin");
842///         match artifact.entry {
843///             true => RelPath::new(format!("paper.{extension}")),
844///             false => RelPath::new(format!("paper-{}.{extension}", artifact.id.name)),
845///         }
846///     }
847/// }
848///
849/// let output = OutputDef::new("html", "flm.artifacts.html", "flm.artifacts.html", "text/html", "html");
850/// let page = Artifact::bytes(ArtifactId::new("html", "page"), "text/html", Vec::new()).as_entry();
851/// let figure = Artifact::bytes(ArtifactId::new("graphics", "fig"), "image/png", Vec::new())
852///     .with_extension("png");
853/// let scope = NamingScope::default();
854/// assert_eq!(path_of(&page, Some(&output), &Paper, &scope).as_str(), "paper.html");
855/// assert_eq!(path_of(&figure, Some(&output), &Paper, &scope).as_str(), "paper-fig.png");
856/// ```
857pub fn path_of(
858    artifact: &Artifact,
859    output: Option<&OutputDef>,
860    namer: &dyn ArtifactNamer,
861    scope: &NamingScope,
862) -> RelPath {
863    if let Some(path) = &artifact.fixed_path {
864        return path.clone();
865    }
866    let extension = match output {
867        Some(output) if artifact.entry => Some(output.entry.extension.as_str()),
868        _ => artifact.extension.as_deref(),
869    };
870    let named = ArtifactRef {
871        id: &artifact.id,
872        entry: artifact.entry,
873        media_type: &artifact.media_type,
874        extension,
875        output: output.map(|output| output.name.as_str()),
876        folder: matches!(artifact.data, ArtifactData::Files(_)),
877    };
878    namer.url_of(&named, scope)
879}
880
881/// Returns the media type of a file by its extension `extension`, written
882/// without the dot, or `None` for an extension this table does not list.
883///
884/// The table lists `html`, `css`, `js`, `txt`, `json`, `svg`, `png`, `jpg` and
885/// `jpeg`, `gif`, `webp`, `pdf`, `tex`, `sty`, `bib`, `woff`, `woff2` and
886/// `ico`; the extension is compared without regard to case. A compose
887/// template's file whose description gives no media type takes the one this
888/// table gives.
889///
890/// # Examples
891///
892/// ```
893/// use flm_core::core::artifact::media_type_of;
894///
895/// assert_eq!(media_type_of("css"), Some("text/css"));
896/// assert_eq!(media_type_of("PNG"), Some("image/png"));
897/// assert_eq!(media_type_of("webmanifest"), None);
898/// ```
899pub fn media_type_of(extension: &str) -> Option<&'static str> {
900    Some(match extension.to_ascii_lowercase().as_str() {
901        "html" => "text/html",
902        "css" => "text/css",
903        "js" => "text/javascript",
904        "txt" => "text/plain",
905        "json" => "application/json",
906        "svg" => "image/svg+xml",
907        "png" => "image/png",
908        "jpg" | "jpeg" => "image/jpeg",
909        "gif" => "image/gif",
910        "webp" => "image/webp",
911        "pdf" => "application/pdf",
912        "tex" | "sty" => "application/x-latex",
913        "bib" => "application/x-bibtex",
914        "woff" => "font/woff",
915        "woff2" => "font/woff2",
916        "ico" => "image/vnd.microsoft.icon",
917        _ => return None,
918    })
919}
920
921#[cfg(test)]
922mod tests {
923    use super::*;
924
925    fn artifact(name: &str) -> Artifact {
926        Artifact::bytes(ArtifactId::new("text", name), "text/plain", b"x".to_vec())
927    }
928
929    #[test]
930    fn a_second_entry_is_refused_at_insert_and_recorded_at_absorb() {
931        let mut set = ArtifactSet::new();
932        set.insert(artifact("document").as_entry()).unwrap();
933        let refused = set.insert(artifact("other").as_entry()).unwrap_err();
934        assert!(matches!(refused, ArtifactSetViolation::SecondEntry { .. }));
935        let mut piece = ArtifactSet::new();
936        piece.insert(artifact("also").as_entry()).unwrap();
937        set.absorb(piece);
938        assert_eq!(set.violations().len(), 1);
939        assert_eq!(set.entry().map(|a| a.id.name.as_str()), Some("document"));
940        assert_eq!(set.len(), 2);
941    }
942
943    #[test]
944    fn the_same_artifact_twice_is_one_and_two_under_one_identity_are_reported() {
945        let mut first = ArtifactSet::new();
946        first.insert(artifact("copy")).unwrap();
947        let mut again = ArtifactSet::new();
948        again.insert(artifact("copy")).unwrap();
949        let mut other = ArtifactSet::new();
950        other.insert(Artifact::bytes(ArtifactId::new("text", "copy"), "text/plain", b"y".to_vec())).unwrap();
951        let mut set = ArtifactSet::new();
952        let reports = set.insert_entry_with(artifact("document").as_entry(), &[&first, &again]).unwrap();
953        assert!(reports.is_empty());
954        assert_eq!(set.len(), 2);
955        let mut set = ArtifactSet::new();
956        let reports = set.insert_entry_with(artifact("document").as_entry(), &[&first, &other]).unwrap();
957        assert_eq!(set.violations(), [ArtifactSetViolation::DuplicateId(ArtifactId::new("text", "copy"))]);
958        assert_eq!(reports.len(), 1);
959        assert_eq!(set.get(&ArtifactId::new("text", "copy")).and_then(Artifact::as_bytes), Some(&b"x"[..]));
960    }
961
962    /// Writes what it is asked: `NAME.EXT`, `NAME/` for a folder, `!` before the name of an
963    /// entry artifact and `@OUTPUT/` before an artifact of a known output.
964    struct Echo;
965
966    impl ArtifactNamer for Echo {
967        fn url_of(&self, artifact: &ArtifactRef<'_>, _: &NamingScope) -> RelPath {
968            let output = artifact.output.map(|output| format!("@{output}/")).unwrap_or_default();
969            let entry = if artifact.entry { "!" } else { "" };
970            let tail = match (artifact.folder, artifact.extension) {
971                (true, _) => String::from("/"),
972                (false, Some(extension)) => format!(".{extension}"),
973                (false, None) => String::new(),
974            };
975            RelPath::new(format!("{output}{entry}{}{tail}", artifact.id.name))
976        }
977    }
978
979    #[test]
980    fn the_path_of_an_artifact_is_its_fixed_path_else_the_namer_s_answer() {
981        let output = OutputDef::new("paper", "x.paper", "x.paper", "application/pdf", "pdf");
982        let scope = NamingScope::default();
983        let path = |artifact: &Artifact, output: Option<&OutputDef>| path_of(artifact, output, &Echo, &scope).to_string();
984        let entry = Artifact::bytes(ArtifactId::new("x", "doc"), "text/plain", Vec::new()).with_extension("txt").as_entry();
985        // An entry artifact takes its output's extension; without an output, its own.
986        assert_eq!(path(&entry, Some(&output)), "@paper/!doc.pdf");
987        assert_eq!(path(&entry, None), "!doc.txt");
988        let other = Artifact::bytes(ArtifactId::new("x", "fig"), "image/png", Vec::new()).with_extension("png");
989        assert_eq!(path(&other, Some(&output)), "@paper/fig.png");
990        let folder = Artifact::folder(ArtifactId::new("x", "icons"), vec![(RelPath::new("a.svg"), Vec::new())]);
991        assert_eq!(path(&folder, None), "icons/");
992        let mut fixed = other.clone();
993        fixed.fixed_path = Some(RelPath::new("fixed/fig.png"));
994        assert_eq!(path(&fixed, Some(&output)), "fixed/fig.png");
995    }
996}