flm_core/model/names.rs
1//! Dotted names, which identify every entity registered with the library, and
2//! one Rust type per kind of name.
3//!
4//! A **name** is a string, usually dotted and by convention lowercase, whose
5//! first segment says who owns it: `flm` for the standard features, a prefix of
6//! its own for anything a third party writes. Capabilities, tables, stages,
7//! lowering rules, features, backends, workflows and outputs are identified by
8//! their names, never by a Rust type. An element also has a name, its type name
9//! ([`ElementName`]), but it is identified by its element value (see
10//! [`ElementSpec`](crate::model::element::ElementSpec)). The reference kind of
11//! a reference point ([`RefKind`]) is a name too. See [names and
12//! identity](crate::guide::concepts_overview#names-and-identity).
13//!
14//! [`Name`] is the shared representation: a shared string (`Arc<str>`) that
15//! compares, hashes and orders by its text. Each kind of name has a type of its
16//! own that wraps a [`Name`] ([`ElementName`], [`CapName`], [`StageName`],
17//! [`RuleName`], [`FeatureName`], [`BackendName`], [`WorkflowName`],
18//! [`OutputName`], [`RefKind`]), so that a function that asks for a capability
19//! name cannot be given a stage name by mistake. Every one of these types
20//! converts from a string literal, so a declaration can write
21//! `"flm.refs.resolved".into()`.
22//!
23//! A name owns its text rather than borrowing a `&'static str`, because a name
24//! may be computed while the registry is built: the name of a theorem
25//! environment declared in a configuration, a table created once per backend
26//! (`flm.lowered.<backend>`), a stage created once per kind of note
27//! (`flm.xnotes.build-list.<kind>`).
28//!
29//! Every name type is written to and read from data (serde) as its plain text,
30//! so that [settings](crate::core::settings) given as data can hold names.
31//!
32//! # Examples
33//!
34//! ```
35//! use flm_core::model::names::{CapName, Name, StageName};
36//!
37//! let stage: StageName = "flm.blocks.structure".into();
38//! let provided: CapName = "flm.blocks.structured".into();
39//! assert_eq!(stage.owner_prefix(), "flm");
40//! assert_eq!(provided.as_str(), "flm.blocks.structured");
41//! // Every name type dereferences to the `Name` it wraps.
42//! assert_eq!(&*stage, &Name::from("flm.blocks.structure"));
43//! ```
44
45use std::borrow::Borrow;
46use std::fmt;
47use std::ops::Deref;
48use std::sync::Arc;
49
50/// A name: a string, usually dotted, whose first segment says who owns
51/// it, such as `flm.heading`, `flm.refs.resolved` or `thm.numbered`.
52///
53/// `Name` compares, hashes and orders by its text, like a `String`, and
54/// cloning one only increments a reference count. Every name type of this
55/// module ([`ElementName`], [`CapName`], …) wraps a `Name` and dereferences to
56/// it. See the [module documentation](self) for what names identify.
57#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
58pub struct Name(Arc<str>);
59
60impl Name {
61 /// Creates a name holding `text`. No check is made on the text.
62 pub fn new(text: impl Into<Arc<str>>) -> Name {
63 Name(text.into())
64 }
65
66 /// The name's text.
67 pub fn as_str(&self) -> &str {
68 &self.0
69 }
70
71 /// The owner prefix: the text before the first dot (`flm` in
72 /// `flm.heading`, `thm` in `thm.numbered`), or the whole name when it holds
73 /// no dot.
74 ///
75 /// By convention, the prefix says who owns the name: `flm` for the
76 /// standard features, another prefix for a third party.
77 pub fn owner_prefix(&self) -> &str {
78 self.0.split('.').next().unwrap_or(&self.0)
79 }
80}
81
82impl Deref for Name {
83 type Target = str;
84
85 fn deref(&self) -> &str {
86 &self.0
87 }
88}
89
90impl Borrow<str> for Name {
91 fn borrow(&self) -> &str {
92 &self.0
93 }
94}
95
96impl AsRef<str> for Name {
97 fn as_ref(&self) -> &str {
98 &self.0
99 }
100}
101
102impl From<&str> for Name {
103 fn from(text: &str) -> Name {
104 Name(Arc::from(text))
105 }
106}
107
108impl From<String> for Name {
109 fn from(text: String) -> Name {
110 Name(Arc::from(text))
111 }
112}
113
114impl From<Arc<str>> for Name {
115 fn from(text: Arc<str>) -> Name {
116 Name(text)
117 }
118}
119
120impl From<&Name> for Name {
121 fn from(name: &Name) -> Name {
122 name.clone()
123 }
124}
125
126/// The shared text of a name, given up without a copy of the text.
127impl From<Name> for Arc<str> {
128 fn from(name: Name) -> Arc<str> {
129 name.0
130 }
131}
132
133impl PartialEq<str> for Name {
134 fn eq(&self, other: &str) -> bool {
135 &*self.0 == other
136 }
137}
138
139impl PartialEq<&str> for Name {
140 fn eq(&self, other: &&str) -> bool {
141 &*self.0 == *other
142 }
143}
144
145impl fmt::Display for Name {
146 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147 f.write_str(&self.0)
148 }
149}
150
151/// Reads a name from data as a string, so that settings given as data
152/// (see [`crate::core::settings`]) can hold names.
153impl<'de> serde::Deserialize<'de> for Name {
154 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Name, D::Error> {
155 String::deserialize(deserializer).map(Name::from)
156 }
157}
158
159/// Writes a name to data as a string.
160impl serde::Serialize for Name {
161 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
162 serializer.serialize_str(self.as_str())
163 }
164}
165
166/// Describes a name in a JSON schema as a string.
167impl schemars::JsonSchema for Name {
168 fn schema_name() -> std::borrow::Cow<'static, str> {
169 "String".into()
170 }
171
172 fn inline_schema() -> bool {
173 true
174 }
175
176 fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
177 String::json_schema(generator)
178 }
179}
180
181impl fmt::Debug for Name {
182 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183 write!(f, "{:?}", &*self.0)
184 }
185}
186
187/// Declares the name type of one kind of name: a type wrapping a [`Name`].
188///
189/// Every type declared this way converts from `&str`, `String`, `Arc<str>` and
190/// [`Name`], and into [`Name`]; dereferences to [`Name`] (and therefore to
191/// `str`); displays as its text; compares, hashes and orders by its text; and
192/// is written to and read from data as a string.
193macro_rules! name_newtype {
194 ($(#[$meta:meta])* $newtype:ident) => {
195 $(#[$meta])*
196 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
197 #[repr(transparent)]
198 pub struct $newtype(pub Name);
199
200 impl $newtype {
201 /// Creates a name holding `text`. No check is made on the text.
202 pub fn new(text: impl Into<Arc<str>>) -> $newtype {
203 $newtype(Name::new(text))
204 }
205
206 /// The [`Name`] this name wraps.
207 pub fn name(&self) -> &Name {
208 &self.0
209 }
210
211 /// The name's text.
212 pub fn as_str(&self) -> &str {
213 self.0.as_str()
214 }
215 }
216
217 impl Deref for $newtype {
218 type Target = Name;
219
220 fn deref(&self) -> &Name {
221 &self.0
222 }
223 }
224
225 impl Borrow<str> for $newtype {
226 fn borrow(&self) -> &str {
227 self.0.as_str()
228 }
229 }
230
231 impl AsRef<str> for $newtype {
232 fn as_ref(&self) -> &str {
233 self.0.as_str()
234 }
235 }
236
237 impl From<&str> for $newtype {
238 fn from(text: &str) -> $newtype {
239 $newtype(Name::from(text))
240 }
241 }
242
243 impl From<String> for $newtype {
244 fn from(text: String) -> $newtype {
245 $newtype(Name::from(text))
246 }
247 }
248
249 impl From<Arc<str>> for $newtype {
250 fn from(text: Arc<str>) -> $newtype {
251 $newtype(Name::from(text))
252 }
253 }
254
255 impl From<Name> for $newtype {
256 fn from(name: Name) -> $newtype {
257 $newtype(name)
258 }
259 }
260
261 impl From<$newtype> for Name {
262 fn from(newtype: $newtype) -> Name {
263 newtype.0
264 }
265 }
266
267 impl PartialEq<str> for $newtype {
268 fn eq(&self, other: &str) -> bool {
269 self.0.as_str() == other
270 }
271 }
272
273 impl PartialEq<&str> for $newtype {
274 fn eq(&self, other: &&str) -> bool {
275 self.0.as_str() == *other
276 }
277 }
278
279 impl<'de> serde::Deserialize<'de> for $newtype {
280 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<$newtype, D::Error> {
281 String::deserialize(deserializer).map($newtype::from)
282 }
283 }
284
285 impl serde::Serialize for $newtype {
286 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
287 serializer.serialize_str(self.as_str())
288 }
289 }
290
291 impl schemars::JsonSchema for $newtype {
292 fn schema_name() -> std::borrow::Cow<'static, str> {
293 "String".into()
294 }
295
296 fn inline_schema() -> bool {
297 true
298 }
299
300 fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
301 String::json_schema(generator)
302 }
303 }
304
305 impl fmt::Display for $newtype {
306 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
307 fmt::Display::fmt(&self.0, f)
308 }
309 }
310
311 impl fmt::Debug for $newtype {
312 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
313 write!(f, "{}({:?})", stringify!($newtype), self.0.as_str())
314 }
315 }
316 };
317}
318
319name_newtype! {
320 /// The type name of an element, which says what kind of thing a node is:
321 /// `flm.heading`, `flm.pres.block`, `thm.exercise`.
322 ///
323 /// Several element values may share one type name and differ in their data
324 /// (every heading level is an element value of type `flm.heading`); an
325 /// element is identified by its value, not by this name. See
326 /// [`ElementSpec`](crate::model::element::ElementSpec).
327 ElementName
328}
329
330name_newtype! {
331 /// The reference kind of a reference point, which says what sort of thing
332 /// the point is: `section`, `equation`, `theorem`
333 /// ([`RefPoint::kind`](crate::model::aspects::RefPoint::kind)).
334 ///
335 /// The set of kinds is open: a feature uses the kinds it needs. A reference
336 /// kind is not the label type that an author writes before the colon of a
337 /// label such as `sec:intro`; the point declares separately which label
338 /// types it accepts (see [`Label`](crate::model::aspects::Label) and
339 /// [`AcceptedRefTypes`](crate::model::aspects::AcceptedRefTypes)).
340 RefKind
341}
342
343name_newtype! {
344 /// The name of a capability, such as `flm.refs.resolved`.
345 ///
346 /// A capability is a registered dotted name for a state of processing that
347 /// a stage brings about: a stage declares the capabilities it provides and
348 /// the capabilities it requires, and a caller demands the capabilities it
349 /// wants ([`CapabilityDef`](crate::core::registry::CapabilityDef)).
350 /// Capabilities and computed tables share one set of names: a table's name
351 /// is also the capability "this table has been computed".
352 CapName
353}
354
355name_newtype! {
356 /// The name of a [stage](crate::core::stage::Stage).
357 ///
358 /// The standard features write it `flm.<feature>.<verb>`: the stage
359 /// `flm.blocks.structure` provides the capability `flm.blocks.structured`.
360 StageName
361}
362
363name_newtype! {
364 /// The name of a [lowering rule](crate::core::lowering::LoweringRule).
365 ///
366 /// The standard features write it `<element>.lower.<variant>`, the type
367 /// name of the element the rule lowers followed by `lower` and the
368 /// variant: `flm.cells.cell.lower.default`.
369 RuleName
370}
371
372name_newtype! {
373 /// The registered name of a [feature](crate::core::registry::FlmFeature):
374 /// `refs`, `theorems`, `htmlplus`.
375 ///
376 /// The standard features use it as the second segment of the names of
377 /// their stages and their diagnostics (`flm.refs.resolve`).
378 FeatureName
379}
380
381name_newtype! {
382 /// The name of a [backend](crate::core::registry::BackendDef), the
383 /// registration bundle for one output format, such as `text` or `html`.
384 ///
385 /// Registering a backend derives from this name the names of what belongs
386 /// to it, such as its table of lowered trees `flm.lowered.<backend>`.
387 BackendName
388}
389
390name_newtype! {
391 /// The name of a workflow, such as `text` or `check`.
392 ///
393 /// A workflow is a named set of demands together with the choices that go
394 /// with them, which a caller selects by name instead of listing
395 /// capabilities ([`WorkflowDef`](crate::core::registry::WorkflowDef)).
396 WorkflowName
397}
398
399name_newtype! {
400 /// The name of an output, such as `text` or `html`: a result a caller can
401 /// ask for, registered with what producing it means
402 /// ([`OutputDef`](crate::core::registry::OutputDef)).
403 ///
404 /// The `flm` command-line program accepts these names as the values of its
405 /// `--format` option.
406 OutputName
407}
408
409#[cfg(test)]
410mod tests {
411 use super::*;
412 use std::collections::BTreeSet;
413
414 #[test]
415 fn names_compare_by_text() {
416 let a = Name::from("flm.heading");
417 let b = Name::new(String::from("flm.heading"));
418 assert_eq!(a, b);
419 assert_eq!(a, "flm.heading");
420 assert_eq!(a.owner_prefix(), "flm");
421 assert_eq!(Name::from("plain").owner_prefix(), "plain");
422 }
423
424 #[test]
425 fn newtypes_convert_and_order() {
426 let cap: CapName = "flm.refs.resolved".into();
427 let cap2 = CapName::from(Name::from("flm.refs.resolved"));
428 assert_eq!(cap, cap2);
429 assert_eq!(cap.as_str(), "flm.refs.resolved");
430 assert_eq!(&*cap, &Name::from("flm.refs.resolved"));
431 let set: BTreeSet<StageName> =
432 ["b.x", "a.y"].into_iter().map(StageName::from).collect();
433 let ordered: Vec<&str> = set.iter().map(|n| n.as_str()).collect();
434 assert_eq!(ordered, ["a.y", "b.x"]);
435 assert_eq!(format!("{}", cap), "flm.refs.resolved");
436 assert_eq!(format!("{:?}", cap), "CapName(\"flm.refs.resolved\")");
437 }
438}