Skip to main content

music21/metadata/
mod.rs

1//! A score's metadata: music21's `metadata.Metadata`.
2//!
3//! music21 keeps metadata as named values, each name a *unique name* from a
4//! fixed vocabulary drawn from Dublin Core, the MARC relator terms and
5//! Humdrum's reference records, or one a caller made up. A name may carry
6//! several values, and the names keep the order they were first given in,
7//! which is the order a MusicXML writer puts them out in.
8//!
9//! A contributor is a value with a role: the composer, an arranger, a
10//! lyricist. Its unique name is its role where the role is in the
11//! vocabulary, and `otherContributor` where it is not.
12
13pub mod bundles;
14pub mod primitives;
15pub mod rich;
16
17use std::borrow::Cow;
18
19/// What a metadata value says beyond its text and its role: one of
20/// music21's primitives.
21#[derive(Clone, Debug, PartialEq, Eq)]
22#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
23pub enum MetadataContent {
24    /// A piece of text with the language it is written in: music21's
25    /// `Text`, and its `Copyright` where the text carries a role.
26    Text(primitives::Text),
27    /// Somebody who had a hand in the work: music21's `Contributor`, which
28    /// may go under several names and may say when they lived.
29    Contributor(primitives::Contributor),
30    /// A date, which may be approximate, uncertain, a bound, a span or a
31    /// choice: music21's `DatePrimitive` and the four classes under it.
32    Date(primitives::DatePrimitive),
33}
34
35/// One value of a metadata name: its text and, for a contributor or a
36/// copyright, the role it was given -- and the primitive it is, which says
37/// what more is known about it.
38///
39/// **The text and the role are a reading of the content, not a second copy
40/// of it.** Every way of building one of these fills all three together and
41/// nothing can write to them afterwards, so they cannot drift apart: a
42/// contributor's text is the first name they go by, and a date's is the way
43/// music21 writes it.
44///
45/// A value built as a plain text is not equal to one built as a contributor
46/// or a date of the same text, and that is right: the one knows what it is
47/// and the other does not.
48#[derive(Clone, Debug, PartialEq, Eq)]
49#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
50pub struct MetadataValue {
51    text: String,
52    role: Option<String>,
53    content: MetadataContent,
54}
55
56impl MetadataValue {
57    /// A value that is only text.
58    pub fn new(text: impl Into<String>) -> Self {
59        Self::of_text(primitives::Text::new(text))
60    }
61
62    /// A value with a role, as a contributor or a copyright has.
63    pub fn with_role(text: impl Into<String>, role: impl Into<String>) -> Self {
64        Self::of_text(primitives::Text::new(text).in_role(role))
65    }
66
67    /// A value that is a piece of text saying what language it is in:
68    /// music21's `Text`, or its `Copyright` where the text has a role.
69    pub fn of_text(text: primitives::Text) -> Self {
70        Self {
71            text: text.data().to_string(),
72            role: text.role().map(str::to_string),
73            content: MetadataContent::Text(text),
74        }
75    }
76
77    /// A value that is somebody who had a hand in the work: music21's
78    /// `Contributor`. Its text is the first name they go by, which is what
79    /// music21's own writers write.
80    pub fn of_contributor(contributor: primitives::Contributor) -> Self {
81        Self {
82            text: contributor
83                .name()
84                .map(primitives::Text::data)
85                .unwrap_or_default()
86                .to_string(),
87            role: contributor.role().map(str::to_string),
88            content: MetadataContent::Contributor(contributor),
89        }
90    }
91
92    /// A value that is a date: music21's four date classes. Its text is
93    /// the way music21 writes that date.
94    pub fn of_date(date: primitives::DatePrimitive) -> Self {
95        Self {
96            text: date.to_string(),
97            role: None,
98            content: MetadataContent::Date(date),
99        }
100    }
101
102    /// The value as text: music21's `str(value)`.
103    pub fn text(&self) -> &str {
104        &self.text
105    }
106
107    /// The role, where the value has one.
108    pub fn role(&self) -> Option<&str> {
109        self.role.as_deref()
110    }
111
112    /// What the value is: a text, a contributor or a date.
113    pub fn content(&self) -> &MetadataContent {
114        &self.content
115    }
116
117    /// The text with its language, where the value is one.
118    pub fn as_text(&self) -> Option<&primitives::Text> {
119        match &self.content {
120            MetadataContent::Text(text) => Some(text),
121            _ => None,
122        }
123    }
124
125    /// The contributor, where the value is one.
126    pub fn as_contributor(&self) -> Option<&primitives::Contributor> {
127        match &self.content {
128            MetadataContent::Contributor(contributor) => Some(contributor),
129            _ => None,
130        }
131    }
132
133    /// The date, where the value is one.
134    pub fn as_date(&self) -> Option<&primitives::DatePrimitive> {
135        match &self.content {
136            MetadataContent::Date(date) => Some(date),
137            _ => None,
138        }
139    }
140}
141
142/// A score's metadata: named values in the order the names were first given.
143///
144/// ```
145/// use music21::metadata::Metadata;
146///
147/// let mut md = Metadata::new();
148/// md.add_text("title", "Wer nur den lieben Gott");
149/// md.add_contributor("composer", "J. S. Bach");
150/// assert_eq!(md.first_text("title"), Some("Wer nur den lieben Gott"));
151/// assert_eq!(md.contributors().next().map(|(_, value)| value.text()), Some("J. S. Bach"));
152/// ```
153#[derive(Clone, Debug, Default, PartialEq, Eq)]
154#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
155#[must_use]
156pub struct Metadata {
157    entries: Vec<(String, Vec<MetadataValue>)>,
158}
159
160impl Metadata {
161    /// Metadata with nothing in it.
162    ///
163    /// music21's own constructor starts with its version under `software`;
164    /// this one starts empty, and a caller who wants a software line adds it.
165    pub fn new() -> Self {
166        Self::default()
167    }
168
169    /// Adds a value under a unique name, after any it already has.
170    pub fn add(&mut self, unique_name: impl Into<String>, value: MetadataValue) {
171        let unique_name = unique_name.into();
172        match self
173            .entries
174            .iter_mut()
175            .find(|(name, _)| *name == unique_name)
176        {
177            Some((_, values)) => values.push(value),
178            None => self.entries.push((unique_name, vec![value])),
179        }
180    }
181
182    /// Adds a value that is only text.
183    pub fn add_text(&mut self, unique_name: impl Into<String>, text: impl Into<String>) {
184        self.add(unique_name, MetadataValue::new(text));
185    }
186
187    /// Adds a contributor in a role: under the role itself where it is one
188    /// of the vocabulary's contributor names, and under `otherContributor`
189    /// where it is not, as music21's `addContributor` files one.
190    pub fn add_contributor(&mut self, role: impl Into<String>, name: impl Into<String>) {
191        let role = role.into();
192        let unique_name = if is_contributor_unique_name(&role) {
193            role.clone()
194        } else {
195            "otherContributor".to_string()
196        };
197        self.add(unique_name, MetadataValue::with_role(name, role));
198    }
199
200    /// Replaces every value under a unique name.
201    pub fn set(&mut self, unique_name: impl Into<String>, values: Vec<MetadataValue>) {
202        let unique_name = unique_name.into();
203        self.entries.retain(|(name, _)| *name != unique_name);
204        if !values.is_empty() {
205            self.entries.push((unique_name, values));
206        }
207    }
208
209    /// Every value under a unique name, in the order they were added.
210    pub fn get(&self, unique_name: &str) -> &[MetadataValue] {
211        self.entries
212            .iter()
213            .find(|(name, _)| name == unique_name)
214            .map_or(&[], |(_, values)| values.as_slice())
215    }
216
217    /// The text of the first value under a unique name.
218    pub fn first_text(&self, unique_name: &str) -> Option<&str> {
219        self.get(unique_name).first().map(MetadataValue::text)
220    }
221
222    /// Every name and value in order, names in the order they were first
223    /// given and each name's values together: music21's `all` with
224    /// `returnSorted=False`.
225    pub fn all(&self) -> impl Iterator<Item = (&str, &MetadataValue)> {
226        self.entries
227            .iter()
228            .flat_map(|(name, values)| values.iter().map(move |value| (name.as_str(), value)))
229    }
230
231    /// The contributors alone, in the same order.
232    pub fn contributors(&self) -> impl Iterator<Item = (&str, &MetadataValue)> {
233        self.all()
234            .filter(|(name, _)| is_contributor_unique_name(name))
235    }
236
237    /// Every value under a unique name as one piece of text, as music21's
238    /// attribute of that name reads it -- `title`, `composer`, `movementName`:
239    /// one contributor by name, two joined with `and`, more as the first
240    /// `and` how many others; a title's values each with an article written
241    /// after a comma put back in front; anything else the values joined with
242    /// commas. Nothing for a name outside the vocabulary, or with no value.
243    pub fn string_value(&self, unique_name: &str) -> Option<String> {
244        namespace_name(unique_name)?;
245        let values = self.get(unique_name);
246        if values.is_empty() {
247            return None;
248        }
249        if is_contributor_unique_name(unique_name) {
250            return Some(match values {
251                [only] => only.text().to_string(),
252                [first, second] => format!("{} and {}", first.text(), second.text()),
253                [first, rest @ ..] => format!("{} and {} others", first.text(), rest.len()),
254                [] => String::new(),
255            });
256        }
257        let texts: Vec<String> = if ARTICLED_TITLES.contains(&unique_name) {
258            values
259                .iter()
260                .map(|value| {
261                    crate::text::prepend_article(value.text(), None)
262                        .unwrap_or_else(|_| value.text().to_string())
263                })
264                .collect()
265        } else {
266            values
267                .iter()
268                .map(|value| value.text().to_string())
269                .collect()
270        };
271        Some(texts.join(", "))
272    }
273
274    /// The title, as [`Self::string_value`] reads it: music21's `title`.
275    pub fn title(&self) -> Option<String> {
276        self.string_value("title")
277    }
278
279    /// The title, or the next best thing the score says: music21's
280    /// `bestTitle`, which takes the first of `title`, `popularTitle`,
281    /// `alternativeTitle` and `movementName` that says anything.
282    ///
283    /// ```
284    /// use music21::metadata::Metadata;
285    ///
286    /// let mut said = Metadata::new();
287    /// said.add_text("popularTitle", "Eroica");
288    /// assert_eq!(said.best_title().as_deref(), Some("Eroica"));
289    /// said.add_text("title", "Third Symphony");
290    /// assert_eq!(said.best_title().as_deref(), Some("Third Symphony"));
291    /// assert_eq!(Metadata::new().best_title(), None);
292    /// ```
293    pub fn best_title(&self) -> Option<String> {
294        ["title", "popularTitle", "alternativeTitle", "movementName"]
295            .into_iter()
296            .find_map(|name| self.string_value(name).filter(|text| !text.is_empty()))
297    }
298
299    /// The contributors in a role, or the ones with no role of their own
300    /// where none is asked for: music21's `getContributorsByRole`, which a
301    /// MusicXML file needs because some of them name a contributor and no
302    /// role.
303    pub fn contributors_by_role(&self, role: Option<&str>) -> Vec<&MetadataValue> {
304        self.contributors()
305            .filter(|(_, value)| value.role() == role)
306            .map(|(_, value)| value)
307            .collect()
308    }
309
310    /// Whether nothing is in it.
311    pub fn is_empty(&self) -> bool {
312        self.entries.is_empty()
313    }
314
315    /// Every name and value sorted by name and then by text, as music21's
316    /// `all` reads them by default and [`Self::search`] walks them.
317    pub fn all_sorted(&self) -> Vec<(&str, &MetadataValue)> {
318        let mut all: Vec<(&str, &MetadataValue)> = self.all().collect();
319        all.sort_by(|(left, left_value), (right, right_value)| {
320            left.cmp(right)
321                .then_with(|| left_value.text().cmp(right_value.text()))
322        });
323        all
324    }
325
326    /// The first value a query matches, and the field it was found under:
327    /// music21's `search`.
328    ///
329    /// With no `field`, every standard name is searched, sorted by name,
330    /// and then every contributor in the order they were added, under its
331    /// role rather than its unique name so that a made-up role can be
332    /// searched for.
333    ///
334    /// A `field` names where to look, and need not be the whole name:
335    /// music21 takes a unique name, one of its four grandfathered work ids
336    /// (`date`, `volume`, `dedication`, `commission`), one of its twenty
337    /// Humdrum abbreviations (`otl`, `ode`), or any piece of a name --
338    /// `compos` finds `composer`. A field naming nothing finds nothing.
339    ///
340    /// ```
341    /// use music21::metadata::{Metadata, MetadataQuery};
342    ///
343    /// let mut md = Metadata::new();
344    /// md.add_contributor("composer", "Joplin, Scott");
345    /// md.add_text("title", "Maple Leaf Rag");
346    ///
347    /// let joplin = MetadataQuery::Text("joplin");
348    /// assert_eq!(
349    ///     md.search(&joplin, Some("composer")).unwrap().field(),
350    ///     Some("composer")
351    /// );
352    /// assert_eq!(
353    ///     md.search(&joplin, Some("compos")).unwrap().field(),
354    ///     Some("composer")
355    /// );
356    /// assert!(md.search(&joplin, Some("title")).is_none());
357    ///
358    /// let found = md.search(&MetadataQuery::Text("leaf"), None).unwrap();
359    /// assert_eq!((found.field(), found.text()), (Some("title"), "Maple Leaf Rag"));
360    /// ```
361    pub fn search(
362        &self,
363        query: &MetadataQuery<'_>,
364        field: Option<&str>,
365    ) -> Option<MetadataMatch<'_>> {
366        let field = field.map(str::to_lowercase);
367        self.search_fields(field.as_deref())
368            .into_iter()
369            .find(|(text, _)| query.matches(text))
370            .map(|(text, field)| MetadataMatch { field, text })
371    }
372
373    /// The text a search looks through and the field each piece answers
374    /// under, in the order music21 builds them.
375    fn search_fields(&self, field: Option<&str>) -> Vec<(Cow<'_, str>, Option<&str>)> {
376        let mut pairs: Vec<(Cow<'_, str>, Option<&str>)> = Vec::new();
377        match field {
378            Some(field) => {
379                let named = unique_name_of_field(field);
380                let texts =
381                    named.map_or_else(Vec::new, |(unique_name, _)| self.field_texts(unique_name));
382                match (texts.is_empty(), named) {
383                    // music21 answers under the field as it was asked for,
384                    // not under the unique name that field stands for.
385                    (false, Some((_, asked))) => {
386                        pairs.extend(texts.into_iter().map(|text| (text, Some(asked))));
387                    }
388                    _ => pairs.extend(self.partial_field_match(field)),
389                }
390            }
391            None => pairs.extend(
392                self.standard_non_contributors()
393                    .map(|(name, value)| (Cow::Borrowed(value.text()), Some(name))),
394            ),
395        }
396        pairs.extend(
397            self.contributors()
398                .filter(|(_, value)| contributor_answers_to(value.role(), field))
399                .map(|(_, value)| (Cow::Borrowed(value.text()), value.role())),
400        );
401        pairs
402    }
403
404    /// A name's values as a search of that name alone reads them: a
405    /// title-like name's article written back in front, which music21's
406    /// `_getStringValuesByNamespaceName` does and the rest of a search
407    /// does not, so that a title stored as `Grassy Turf, The` is searched
408    /// as `The Grassy Turf` under `title` and as itself under every field.
409    pub(crate) fn field_texts(&self, unique_name: &str) -> Vec<Cow<'_, str>> {
410        self.get(unique_name)
411            .iter()
412            .map(|value| {
413                if ARTICLED_TITLES.contains(&unique_name) {
414                    Cow::Owned(
415                        crate::text::prepend_article(value.text(), None)
416                            .unwrap_or_else(|_| value.text().to_string()),
417                    )
418                } else {
419                    Cow::Borrowed(value.text())
420                }
421            })
422            .collect()
423    }
424
425    /// The vocabulary's names that are not contributors, sorted, with their
426    /// values: music21's `all(skipContributors=True)` without the names a
427    /// caller made up, which it does not search.
428    fn standard_non_contributors(&self) -> impl Iterator<Item = (&str, &MetadataValue)> {
429        self.all_sorted()
430            .into_iter()
431            .filter(|(name, _)| !is_contributor_unique_name(name) && namespace_name(name).is_some())
432    }
433
434    /// The first standard name holding `field` anywhere in it, with the
435    /// first of that name's values: music21's partial field match, which
436    /// stops at the name it finds and searches that one value alone.
437    fn partial_field_match(&self, field: &str) -> Option<(Cow<'_, str>, Option<&str>)> {
438        self.standard_non_contributors().find_map(|(name, value)| {
439            if name.to_lowercase().contains(field) {
440                return Some((Cow::Borrowed(value.text()), Some(name)));
441            }
442            let work_id = old_work_id(name)?;
443            work_id
444                .to_lowercase()
445                .contains(field)
446                .then_some((Cow::Borrowed(value.text()), Some(work_id)))
447        })
448    }
449}
450
451/// Whether a contributor answers to a search field: every contributor where
452/// none was asked for, one whose role holds the field, and a contributor
453/// with no role only under `contributor` itself.
454pub(crate) fn contributor_answers_to(role: Option<&str>, field: Option<&str>) -> bool {
455    let Some(field) = field else {
456        return true;
457    };
458    match role {
459        None => field == "contributor",
460        Some(role) => role.to_lowercase().contains(field),
461    }
462}
463
464/// The unique name an attribute name stands for: the name itself, one of
465/// music21's four grandfathered work ids, or one of its twenty Humdrum
466/// abbreviations. Nothing for a name outside the vocabulary.
467///
468/// Spelling counts, as it does for music21's own attribute access: `otl`
469/// and `title` both name the title, `OTL` names nothing.
470///
471/// ```
472/// use music21::metadata::unique_name_of;
473///
474/// assert_eq!(unique_name_of("title"), Some("title"));
475/// assert_eq!(unique_name_of("otl"), Some("title"));
476/// assert_eq!(unique_name_of("dedication"), Some("dedicatedTo"));
477/// assert_eq!(unique_name_of("OTL"), None);
478/// assert_eq!(unique_name_of("madeUp"), None);
479/// ```
480pub fn unique_name_of(name: &str) -> Option<&'static str> {
481    if let Some((found, _, _)) = STANDARD_PROPERTIES
482        .iter()
483        .find(|(unique, _, _)| *unique == name)
484    {
485        return Some(found);
486    }
487    OLD_MUSIC21_NAMES
488        .iter()
489        .find(|(_, abbreviation, work_id)| *abbreviation == Some(name) || *work_id == Some(name))
490        .map(|(unique, _, _)| *unique)
491}
492
493/// The unique name a search field stands for where it names one outright,
494/// with the spelling it was asked for: the name itself, one of music21's
495/// grandfathered work ids, or one of its Humdrum abbreviations. The field
496/// reaching here is already lowercase, so a name written with a capital in
497/// it is only found by [`Metadata::partial_field_match`], as in music21.
498pub(crate) fn unique_name_of_field(field: &str) -> Option<(&'static str, &'static str)> {
499    if let Some((name, _, _)) = STANDARD_PROPERTIES
500        .iter()
501        .find(|(name, _, _)| *name == field)
502    {
503        return Some((name, name));
504    }
505    OLD_MUSIC21_NAMES
506        .iter()
507        .find_map(
508            |(name, abbreviation, work_id)| match (abbreviation, work_id) {
509                (Some(asked), _) if *asked == field => Some((*name, *asked)),
510                (_, Some(asked)) if *asked == field => Some((*name, *asked)),
511                _ => None,
512            },
513        )
514}
515
516/// The work id a unique name was written as before music21 v8, where it had
517/// one: music21's `UNIQUE_NAME_TO_MUSIC21_WORK_ID`.
518pub(crate) fn old_work_id(unique_name: &str) -> Option<&'static str> {
519    OLD_MUSIC21_NAMES
520        .iter()
521        .find(|(name, _, _)| *name == unique_name)
522        .and_then(|(_, _, work_id)| *work_id)
523}
524
525/// What a [`Metadata::search`] asks of one value's text.
526///
527/// music21 reads a regular expression out of a plain string where it holds
528/// any of `*.|+?{}`, and matches the rest by containment. Nothing here
529/// compiles a pattern -- the crate carries no regular expression engine --
530/// so [`Self::Text`] is music21's plain-string reading alone, and a caller
531/// who wants its regular expression hands over a [`Self::Matcher`] built
532/// from whichever engine they already have.
533pub enum MetadataQuery<'a> {
534    /// A value matches where its text holds this text, either case
535    /// ignored: music21's string query.
536    Text(&'a str),
537    /// A value matches where this answers `true` to its text: music21's
538    /// callable query.
539    Matcher(&'a dyn Fn(&str) -> bool),
540}
541
542impl MetadataQuery<'_> {
543    /// Whether one value's text matches.
544    fn matches(&self, text: &str) -> bool {
545        match self {
546            Self::Text(query) => text.to_lowercase().contains(&query.to_lowercase()),
547            Self::Matcher(matcher) => matcher(text),
548        }
549    }
550}
551
552impl std::fmt::Debug for MetadataQuery<'_> {
553    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
554        match self {
555            Self::Text(query) => formatter.debug_tuple("Text").field(query).finish(),
556            Self::Matcher(_) => formatter.write_str("Matcher(..)"),
557        }
558    }
559}
560
561/// What a [`Metadata::search`] found: the text that matched and the field it
562/// answers under. A contributor with a made-up role answers under that
563/// role, and one with no role at all under no field, which is music21's
564/// `(True, None)`.
565#[derive(Clone, Debug, PartialEq, Eq)]
566pub struct MetadataMatch<'a> {
567    field: Option<&'a str>,
568    text: Cow<'a, str>,
569}
570
571impl<'a> MetadataMatch<'a> {
572    /// The field the value was found under.
573    pub fn field(&self) -> Option<&'a str> {
574        self.field
575    }
576
577    /// The text that matched.
578    pub fn text(&self) -> &str {
579        &self.text
580    }
581}
582
583/// The unique names music21 kept an older spelling of: its
584/// `oldMusic21Abbrev` and `oldMusic21WorkId`, both of which
585/// [`Metadata::search`] takes as a field name. Each row is the unique
586/// name, its Humdrum abbreviation and the work id it was written as
587/// before music21 v8.
588pub const OLD_MUSIC21_NAMES: [(&str, Option<&str>, Option<&str>); 21] = [
589    ("alternativeTitle", Some("ota"), None),
590    ("dateCreated", None, Some("date")),
591    ("title", Some("otl"), None),
592    ("textOriginalLanguage", Some("txo"), None),
593    ("textLanguage", Some("txl"), None),
594    ("popularTitle", Some("otp"), None),
595    ("parentTitle", Some("opr"), None),
596    ("actNumber", Some("oac"), None),
597    ("sceneNumber", Some("osc"), None),
598    ("movementNumber", Some("omv"), None),
599    ("movementName", Some("omd"), None),
600    ("opusNumber", Some("ops"), None),
601    ("number", Some("onm"), None),
602    ("volumeNumber", Some("ovm"), Some("volume")),
603    ("dedicatedTo", Some("ode"), Some("dedication")),
604    ("commissionedBy", Some("oco"), Some("commission")),
605    ("countryOfComposition", Some("ocy"), None),
606    ("localeOfComposition", Some("opc"), None),
607    ("groupTitle", Some("gtl"), None),
608    ("associatedWork", Some("gaw"), None),
609    ("collectionDesignation", Some("gco"), None),
610];
611
612/// The names whose values are titles, an article at their end moved to the
613/// front when read as text: music21's `needsArticleNormalization`.
614const ARTICLED_TITLES: [&str; 6] = [
615    "title",
616    "alternativeTitle",
617    "popularTitle",
618    "parentTitle",
619    "movementName",
620    "groupTitle",
621];
622
623/// The eleven vocabulary names whose value is a date rather than a text:
624/// music21's `valueType=DatePrimitive`.
625const DATE_NAMES: [&str; 11] = [
626    "dateAvailable",
627    "dateCreated",
628    "otherDate",
629    "dateAccepted",
630    "dateCopyrighted",
631    "dateSubmitted",
632    "dateIssued",
633    "dateModified",
634    "dateValid",
635    "dateFirstPublished",
636    "electronicReleaseDate",
637];
638
639/// What kind of value a metadata name takes: music21's
640/// `UNIQUE_NAME_TO_VALUE_TYPE`, which is what its `convertValue` reads to
641/// decide what to make of whatever it was handed.
642#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
643#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
644pub enum ValueKind {
645    /// A piece of text: music21's `Text`, which 64 of the names take.
646    Text,
647    /// A text with a role: music21's `Copyright`, which `copyright`
648    /// alone takes.
649    Copyright,
650    /// Somebody who had a hand in the work: music21's `Contributor`,
651    /// which the 54 contributor names take.
652    Contributor,
653    /// A date: music21's `DatePrimitive` and the four classes under it,
654    /// which the eleven date names take.
655    Date,
656    /// A whole number: `fileNumber` alone takes one.
657    Number,
658}
659
660/// What kind of value a unique name takes, and nothing for a name outside
661/// the vocabulary -- which music21 keeps as a text, there being nothing to
662/// say otherwise.
663///
664/// ```
665/// use music21::metadata::{ValueKind, value_kind_of};
666///
667/// assert_eq!(value_kind_of("title"), Some(ValueKind::Text));
668/// assert_eq!(value_kind_of("composer"), Some(ValueKind::Contributor));
669/// assert_eq!(value_kind_of("dateCreated"), Some(ValueKind::Date));
670/// assert_eq!(value_kind_of("copyright"), Some(ValueKind::Copyright));
671/// assert_eq!(value_kind_of("average duration"), None);
672/// ```
673#[must_use]
674pub fn value_kind_of(name: &str) -> Option<ValueKind> {
675    let unique_name = unique_name_of(name).or_else(|| unique_name_from_namespace(name))?;
676    if unique_name == "copyright" {
677        return Some(ValueKind::Copyright);
678    }
679    if unique_name == "fileNumber" {
680        return Some(ValueKind::Number);
681    }
682    if DATE_NAMES.contains(&unique_name) {
683        return Some(ValueKind::Date);
684    }
685    if is_contributor_unique_name(unique_name) {
686        return Some(ValueKind::Contributor);
687    }
688    Some(ValueKind::Text)
689}
690
691/// Whether a unique name is one of the vocabulary's contributor names:
692/// music21's `_isContributorUniqueName`.
693pub fn is_contributor_unique_name(unique_name: &str) -> bool {
694    STANDARD_PROPERTIES
695        .iter()
696        .any(|(name, _, contributor)| *contributor && *name == unique_name)
697}
698
699/// The namespaced name a unique name stands for, `humdrum:OPC` for
700/// `localeOfComposition`: music21's `uniqueNameToNamespaceName`. A name
701/// outside the vocabulary has none.
702pub fn namespace_name(unique_name: &str) -> Option<&'static str> {
703    STANDARD_PROPERTIES
704        .iter()
705        .find(|(name, _, _)| *name == unique_name)
706        .map(|(_, namespaced, _)| *namespaced)
707}
708
709/// The unique name a namespaced name stands for, `localeOfComposition` for
710/// `humdrum:OPC`: music21's `namespaceNameToUniqueName`. A name outside
711/// the vocabulary stands for none.
712///
713/// ```
714/// use music21::metadata::unique_name_from_namespace;
715///
716/// assert_eq!(unique_name_from_namespace("humdrum:OPC"), Some("localeOfComposition"));
717/// assert_eq!(unique_name_from_namespace("soundtracker:SampleName"), None);
718/// ```
719#[must_use]
720pub fn unique_name_from_namespace(namespaced: &str) -> Option<&'static str> {
721    STANDARD_PROPERTIES
722        .iter()
723        .find(|(_, named, _)| *named == namespaced)
724        .map(|(unique, _, _)| *unique)
725}
726
727/// Whether a name is one the vocabulary knows, by its unique name or by
728/// its namespaced one: music21's `isStandardName`. A name of music21's own
729/// older vocabulary -- a work id or its abbreviation -- is not one of
730/// these, as music21's answer is not either.
731///
732/// ```
733/// use music21::metadata::is_standard_name;
734///
735/// assert!(is_standard_name("librettist"));
736/// assert!(is_standard_name("marcrel:LBT"));
737/// assert!(!is_standard_name("average duration"));
738/// assert!(!is_standard_name("soundtracker:SampleName"));
739/// ```
740#[must_use]
741pub fn is_standard_name(name: &str) -> bool {
742    STANDARD_PROPERTIES
743        .iter()
744        .any(|(unique, named, _)| *unique == name || *named == name)
745}
746
747/// Whether a name is one of the work ids music21 wrote before v8, such
748/// as `date`: music21's `ALL_MUSIC21_WORK_IDS`.
749///
750/// ```
751/// use music21::metadata::is_music21_work_id;
752///
753/// assert!(is_music21_work_id("date"));
754/// assert!(!is_music21_work_id("dateDestroyed"));
755/// ```
756#[must_use]
757pub fn is_music21_work_id(name: &str) -> bool {
758    OLD_MUSIC21_NAMES
759        .iter()
760        .any(|(_, _, work_id)| *work_id == Some(name))
761}
762
763/// The unique name a plural attribute of music21's answers for,
764/// `composer` for `composers`: music21's
765/// `ALL_PLURAL_ATTRIBUTE_NAMES`, each of which answers every value under
766/// the name rather than the first.
767///
768/// ```
769/// use music21::metadata::unique_name_of_plural;
770///
771/// assert_eq!(unique_name_of_plural("composers"), Some("composer"));
772/// assert_eq!(unique_name_of_plural("software"), Some("software"));
773/// assert_eq!(unique_name_of_plural("titles"), None);
774/// ```
775#[must_use]
776pub fn unique_name_of_plural(plural: &str) -> Option<&'static str> {
777    match plural {
778        "composers" => Some("composer"),
779        "librettists" => Some("librettist"),
780        "lyricists" => Some("lyricist"),
781        "software" => Some("software"),
782        _ => None,
783    }
784}
785
786/// One property of the vocabulary as music21's `PropertyDescription`
787/// says it.
788#[derive(Clone, Copy, Debug, PartialEq, Eq)]
789#[non_exhaustive]
790pub struct PropertyDescription {
791    /// The name music21 knows it by, unique in the vocabulary.
792    pub unique_name: &'static str,
793    /// Its name in its namespace, the tail of `dcterms:alternative`.
794    pub name: &'static str,
795    /// The namespace: `dcterms`, `marcrel`, `humdrum`, `m21FileInfo` or
796    /// `music21`.
797    pub namespace: &'static str,
798    /// The Humdrum abbreviation music21 took it by before v8.
799    pub old_abbreviation: Option<&'static str>,
800    /// The work id music21 took it by before v8.
801    pub old_work_id: Option<&'static str>,
802    /// What kind of value it takes.
803    pub value_kind: ValueKind,
804    /// Whether its value is a title whose closing article reads in front.
805    pub needs_article_normalization: bool,
806    /// Whether it names somebody who had a hand in the work.
807    pub is_contributor: bool,
808}
809
810/// music21's `STANDARD_PROPERTY_DESCRIPTIONS`, in its order.
811///
812/// ```
813/// use music21::metadata::property_descriptions;
814///
815/// let alternative = property_descriptions()
816///     .find(|property| property.unique_name == "alternativeTitle")
817///     .unwrap();
818/// assert_eq!((alternative.namespace, alternative.name), ("dcterms", "alternative"));
819/// assert_eq!(alternative.old_abbreviation, Some("ota"));
820/// assert!(alternative.needs_article_normalization);
821/// ```
822pub fn property_descriptions() -> impl Iterator<Item = PropertyDescription> {
823    STANDARD_PROPERTIES
824        .iter()
825        .map(|(unique_name, namespaced, is_contributor)| {
826            let (namespace, name) = namespaced.split_once(':').unwrap_or(("", namespaced));
827            let old = OLD_MUSIC21_NAMES
828                .iter()
829                .find(|(old_name, _, _)| old_name == unique_name);
830            PropertyDescription {
831                unique_name,
832                name,
833                namespace,
834                old_abbreviation: old.and_then(|(_, abbreviation, _)| *abbreviation),
835                old_work_id: old.and_then(|(_, _, work_id)| *work_id),
836                value_kind: value_kind_of(unique_name).unwrap_or(ValueKind::Text),
837                needs_article_normalization: ARTICLED_TITLES.contains(unique_name),
838                is_contributor: *is_contributor,
839            }
840        })
841}
842
843/// music21's `STANDARD_PROPERTY_DESCRIPTIONS`: each property's unique name,
844/// its namespaced name, and whether it names a contributor.
845pub const STANDARD_PROPERTIES: [(&str, &str, bool); 131] = [
846    ("abstract", "dcterms:abstract", false),
847    ("accessRights", "dcterms:accessRights", false),
848    ("alternativeTitle", "dcterms:alternative", false),
849    ("audience", "dcterms:audience", false),
850    ("dateAvailable", "dcterms:available", false),
851    (
852        "bibliographicCitation",
853        "dcterms:bibliographicCitation",
854        false,
855    ),
856    ("conformsTo", "dcterms:conformsTo", false),
857    ("dateCreated", "dcterms:created", false),
858    ("otherDate", "dcterms:date", false),
859    ("dateAccepted", "dcterms:dateAccepted", false),
860    ("dateCopyrighted", "dcterms:dateCopyrighted", false),
861    ("dateSubmitted", "dcterms:dateSubmitted", false),
862    ("description", "dcterms:description", false),
863    ("educationLevel", "dcterms:educationLevel", false),
864    ("extent", "dcterms:extent", false),
865    ("format", "dcterms:format", false),
866    ("hasFormat", "dcterms:hasFormat", false),
867    ("hasPart", "dcterms:hasPart", false),
868    ("hasVersion", "dcterms:hasVersion", false),
869    ("identifier", "dcterms:identifier", false),
870    ("instructionalMethod", "dcterms:instructionalMethod", false),
871    ("isFormatOf", "dcterms:isFormatOf", false),
872    ("isPartOf", "dcterms:isPartOf", false),
873    ("isReferencedBy", "dcterms:isReferencedBy", false),
874    ("isReplacedBy", "dcterms:isReplacedBy", false),
875    ("isRequiredBy", "dcterms:isRequiredBy", false),
876    ("dateIssued", "dcterms:issued", false),
877    ("isVersionOf", "dcterms:isVersionOf", false),
878    ("language", "dcterms:language", false),
879    ("license", "dcterms:license", false),
880    ("medium", "dcterms:medium", false),
881    ("dateModified", "dcterms:modified", false),
882    ("provenance", "dcterms:provenance", false),
883    ("publisher", "dcterms:publisher", true),
884    ("references", "dcterms:references", false),
885    ("relation", "dcterms:relation", false),
886    ("replaces", "dcterms:replaces", false),
887    ("requires", "dcterms:requires", false),
888    ("copyright", "dcterms:rights", false),
889    ("rightsHolder", "dcterms:rightsHolder", true),
890    ("source", "dcterms:source", false),
891    ("subject", "dcterms:subject", false),
892    ("tableOfContents", "dcterms:tableOfContents", false),
893    ("title", "dcterms:title", false),
894    ("type", "dcterms:type", false),
895    ("dateValid", "dcterms:valid", false),
896    ("adapter", "marcrel:ADP", true),
897    ("analyst", "marcrel:ANL", true),
898    ("annotator", "marcrel:ANN", true),
899    ("arranger", "marcrel:ARR", true),
900    ("quotationsAuthor", "marcrel:AQT", true),
901    ("afterwordAuthor", "marcrel:AFT", true),
902    ("dialogAuthor", "marcrel:AUD", true),
903    ("introductionAuthor", "marcrel:AUI", true),
904    ("calligrapher", "marcrel:CLL", true),
905    ("collaborator", "marcrel:CLB", true),
906    ("collotyper", "marcrel:CLT", true),
907    ("commentaryAuthor", "marcrel:CWT", true),
908    ("compiler", "marcrel:COM", true),
909    ("composer", "marcrel:CMP", true),
910    ("conceptor", "marcrel:CCP", true),
911    ("conductor", "marcrel:CND", true),
912    ("otherContributor", "marcrel:CTB", true),
913    ("editor", "marcrel:EDT", true),
914    ("engraver", "marcrel:EGR", true),
915    ("etcher", "marcrel:ETR", true),
916    ("illuminator", "marcrel:ILU", true),
917    ("illustrator", "marcrel:ILL", true),
918    ("instrumentalist", "marcrel:ITR", true),
919    ("librettist", "marcrel:LBT", true),
920    ("lithographer", "marcrel:LTG", true),
921    ("lyricist", "marcrel:LYR", true),
922    ("metalEngraver", "marcrel:MTE", true),
923    ("musician", "marcrel:MUS", true),
924    ("proofreader", "marcrel:PFR", true),
925    ("platemaker", "marcrel:PLT", true),
926    ("printmaker", "marcrel:PRM", true),
927    ("producer", "marcrel:PRO", true),
928    ("responsibleParty", "marcrel:RPY", true),
929    ("scribe", "marcrel:SCR", true),
930    ("singer", "marcrel:SNG", true),
931    ("transcriber", "marcrel:TRC", true),
932    ("translator", "marcrel:TRL", true),
933    ("woodEngraver", "marcrel:WDE", true),
934    ("woodCutter", "marcrel:WDC", true),
935    ("accompanyingMaterialWriter", "marcrel:WAM", true),
936    ("distributor", "marcrel:DST", true),
937    ("software", "musicxml:software", false),
938    ("textOriginalLanguage", "humdrum:TXO", false),
939    ("textLanguage", "humdrum:TXL", false),
940    ("popularTitle", "humdrum:OTP", false),
941    ("parentTitle", "humdrum:OPR", false),
942    ("actNumber", "humdrum:OAC", false),
943    ("sceneNumber", "humdrum:OSC", false),
944    ("movementNumber", "humdrum:OMV", false),
945    ("movementName", "humdrum:OMD", false),
946    ("opusNumber", "humdrum:OPS", false),
947    ("number", "humdrum:ONM", false),
948    ("volumeNumber", "humdrum:OVM", false),
949    ("dedicatedTo", "humdrum:ODE", false),
950    ("commissionedBy", "humdrum:OCO", false),
951    ("countryOfComposition", "humdrum:OCY", false),
952    ("localeOfComposition", "humdrum:OPC", false),
953    ("groupTitle", "humdrum:GTL", false),
954    ("associatedWork", "humdrum:GAW", false),
955    ("collectionDesignation", "humdrum:GCO", false),
956    ("attributedComposer", "humdrum:COA", true),
957    ("suspectedComposer", "humdrum:COS", true),
958    ("composerAlias", "humdrum:COL", true),
959    ("composerCorporate", "humdrum:COC", true),
960    ("orchestrator", "humdrum:LOR", true),
961    ("firstPublisher", "humdrum:PPR", true),
962    ("dateFirstPublished", "humdrum:PDT", false),
963    ("publicationTitle", "humdrum:PTL", false),
964    ("placeFirstPublished", "humdrum:PPP", false),
965    ("publishersCatalogNumber", "humdrum:PC#", false),
966    ("scholarlyCatalogName", "humdrum:SCA", false),
967    ("scholarlyCatalogAbbreviation", "humdrum:SCT", false),
968    ("manuscriptSourceName", "humdrum:SMS", false),
969    ("manuscriptLocation", "humdrum:SML", false),
970    ("manuscriptAccessAcknowledgement", "humdrum:SMA", false),
971    ("originalDocumentOwner", "humdrum:YOO", true),
972    ("originalEditor", "humdrum:YOE", true),
973    ("electronicEditor", "humdrum:EED", true),
974    ("electronicEncoder", "humdrum:ENC", true),
975    ("electronicPublisher", "humdrum:YEP", true),
976    ("electronicReleaseDate", "humdrum:YER", false),
977    ("fileFormat", "m21FileInfo:fileFormat", false),
978    ("filePath", "m21FileInfo:filePath", false),
979    ("corpusFilePath", "m21FileInfo:corpusFilePath", false),
980    ("fileNumber", "m21FileInfo:fileNumber", false),
981];
982
983#[cfg(test)]
984mod tests {
985    use super::*;
986
987    /// Every answer here is music21's own for the same metadata.
988    #[test]
989    fn the_best_title_is_the_first_one_said() {
990        let title = |name: &str, text: &str| {
991            let mut said = Metadata::new();
992            said.add_text(name, text);
993            said.best_title()
994        };
995        assert_eq!(
996            title("title", "Third Symphony").as_deref(),
997            Some("Third Symphony")
998        );
999        assert_eq!(title("popularTitle", "Eroica").as_deref(), Some("Eroica"));
1000        assert_eq!(
1001            title("alternativeTitle", "Bonaparte").as_deref(),
1002            Some("Bonaparte")
1003        );
1004        assert_eq!(title("movementName", "Allegro").as_deref(), Some("Allegro"));
1005        assert_eq!(Metadata::new().best_title(), None);
1006
1007        // The title itself wins over the one it is popularly called.
1008        let mut both = Metadata::new();
1009        both.add_text("popularTitle", "Eroica");
1010        both.add_text("title", "Third Symphony");
1011        assert_eq!(both.best_title().as_deref(), Some("Third Symphony"));
1012    }
1013
1014    /// Every answer here is music21's own for the same contributors.
1015    #[test]
1016    fn contributors_are_found_by_their_role() {
1017        let mut said = Metadata::new();
1018        said.add_text("title", "Violin Concerto");
1019        said.add_contributor("composer", "Price, Florence");
1020        // A contributor with no role of its own, as a MusicXML file may
1021        // name one: music21 files it under `otherContributor`.
1022        said.add("otherContributor", MetadataValue::new("Baron van Swieten"));
1023
1024        let names = |role: Option<&str>| -> Vec<String> {
1025            said.contributors_by_role(role)
1026                .iter()
1027                .map(|value| value.text().to_string())
1028                .collect()
1029        };
1030        assert_eq!(names(Some("composer")), ["Price, Florence"]);
1031        assert_eq!(names(None), ["Baron van Swieten"]);
1032        assert!(names(Some("lyricist")).is_empty());
1033
1034        let mut two = Metadata::new();
1035        two.add_contributor("composer", "A");
1036        two.add_contributor("composer", "B");
1037        assert_eq!(
1038            two.contributors_by_role(Some("composer"))
1039                .iter()
1040                .map(|value| value.text())
1041                .collect::<Vec<&str>>(),
1042            ["A", "B"]
1043        );
1044    }
1045
1046    #[test]
1047    fn names_keep_the_order_they_were_first_given() {
1048        let mut md = Metadata::new();
1049        md.add_text("software", "Finale");
1050        md.add_text("movementName", "Grave");
1051        md.add_text("software", "Dolet");
1052        let all: Vec<(&str, &str)> = md.all().map(|(name, value)| (name, value.text())).collect();
1053        assert_eq!(
1054            all,
1055            [
1056                ("software", "Finale"),
1057                ("software", "Dolet"),
1058                ("movementName", "Grave")
1059            ]
1060        );
1061    }
1062
1063    #[test]
1064    fn a_role_outside_the_vocabulary_is_another_contributor() {
1065        let mut md = Metadata::new();
1066        md.add_contributor("composer", "Caccini");
1067        md.add_contributor("tuba player", "Somebody");
1068        let names: Vec<&str> = md.contributors().map(|(name, _)| name).collect();
1069        assert_eq!(names, ["composer", "otherContributor"]);
1070        assert_eq!(md.get("otherContributor")[0].role(), Some("tuba player"));
1071    }
1072
1073    #[test]
1074    fn a_search_of_one_name_reads_a_title_with_its_article_in_front() {
1075        let mut md = Metadata::new();
1076        md.add_text("title", "Grassy Turf, The");
1077        // music21 normalizes the article only where the field is named
1078        // outright, and leaves the stored text alone everywhere else.
1079        let query = MetadataQuery::Text("The Grassy");
1080        assert_eq!(
1081            md.search(&query, Some("title"))
1082                .map(|found| found.text().to_string()),
1083            Some("The Grassy Turf".to_string())
1084        );
1085        assert!(md.search(&query, None).is_none());
1086        assert!(md.search(&query, Some("titl")).is_none());
1087    }
1088
1089    #[test]
1090    fn a_contributor_answers_under_the_role_it_was_given() {
1091        let mut md = Metadata::new();
1092        md.add_contributor("tuba player", "Somebody");
1093        let query = MetadataQuery::Text("somebody");
1094        assert_eq!(
1095            md.search(&query, None).and_then(|found| found.field()),
1096            Some("tuba player")
1097        );
1098        assert_eq!(
1099            md.search(&query, Some("tuba"))
1100                .and_then(|found| found.field()),
1101            Some("tuba player")
1102        );
1103        // A role of its own is not reached under `contributor`, as in
1104        // music21, which only asks that of a contributor with no role.
1105        assert!(md.search(&query, Some("contributor")).is_none());
1106    }
1107
1108    #[test]
1109    fn a_matcher_searches_where_music21_would_read_a_pattern() {
1110        let mut md = Metadata::new();
1111        md.add_text("title", "Maple Leaf Rag");
1112        md.add_contributor("composer", "Joplin, Scott");
1113        let ends_in_rag = |text: &str| text.ends_with("Rag");
1114        let found = md
1115            .search(&MetadataQuery::Matcher(&ends_in_rag), None)
1116            .expect("the title");
1117        assert_eq!(
1118            (found.field(), found.text()),
1119            (Some("title"), "Maple Leaf Rag")
1120        );
1121        assert!(
1122            md.search(&MetadataQuery::Matcher(&ends_in_rag), Some("composer"))
1123                .is_none()
1124        );
1125    }
1126
1127    #[test]
1128    fn the_vocabulary_names_its_namespaces() {
1129        assert_eq!(namespace_name("localeOfComposition"), Some("humdrum:OPC"));
1130        assert_eq!(namespace_name("dateCreated"), Some("dcterms:created"));
1131        assert_eq!(namespace_name("composer"), Some("marcrel:CMP"));
1132        assert_eq!(namespace_name("madeUp"), None);
1133        assert!(is_contributor_unique_name("lyricist"));
1134        assert!(!is_contributor_unique_name("title"));
1135    }
1136}