Skip to main content

day_core/
element_id.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Declared element identities. `id!` is the only declaration surface; the catalog is
5//! collected at link time, including declarations in helpers which have never mounted.
6use std::borrow::Cow;
7use std::collections::BTreeMap;
8
9/// An application-owned element identity, declared with [`crate::id!`].
10#[derive(Clone, Debug)]
11pub struct ElementId {
12    declaration: &'static Declaration,
13    text: Cow<'static, str>,
14}
15impl PartialEq for ElementId {
16    fn eq(&self, other: &Self) -> bool {
17        self.text == other.text
18    }
19}
20impl Eq for ElementId {}
21
22impl ElementId {
23    #[doc(hidden)]
24    #[must_use]
25    pub fn from_declaration(declaration: &'static Declaration) -> Self {
26        Self {
27            declaration,
28            text: Cow::Borrowed(declaration.family),
29        }
30    }
31    #[doc(hidden)]
32    pub fn with_key(declaration: &'static Declaration, key: impl IntoElementKey) -> Self {
33        let mut text = String::from(declaration.family);
34        text.push(':');
35        for byte in key.into_element_key().bytes() {
36            if byte.is_ascii_alphanumeric() || b"-._~".contains(&byte) {
37                text.push(char::from(byte));
38            } else {
39                const HEX: &[u8] = b"0123456789ABCDEF";
40                text.push('%');
41                text.push(char::from(HEX[(byte >> 4) as usize]));
42                text.push(char::from(HEX[(byte & 15) as usize]));
43            }
44        }
45        Self {
46            declaration,
47            text: Cow::Owned(text),
48        }
49    }
50    #[must_use]
51    pub fn as_str(&self) -> &str {
52        &self.text
53    }
54    #[must_use]
55    pub fn family(&self) -> &'static str {
56        self.declaration.family
57    }
58    #[must_use]
59    pub fn is_keyed(&self) -> bool {
60        self.declaration.keyed
61    }
62}
63
64/// Explicit, stable canonical text for an instance key. No blanket Display conversion.
65/// Integer 42 and text "42" intentionally denote the same key. Composite keys must
66/// define an unambiguous app-owned encoding before the framework percent-escapes it.
67pub trait IntoElementKey {
68    fn into_element_key(self) -> String;
69}
70impl IntoElementKey for String {
71    fn into_element_key(self) -> String {
72        self
73    }
74}
75impl IntoElementKey for &str {
76    fn into_element_key(self) -> String {
77        self.to_owned()
78    }
79}
80impl IntoElementKey for &String {
81    fn into_element_key(self) -> String {
82        self.clone()
83    }
84}
85macro_rules! integer_keys {
86    ($($ty:ty),*) => { $(impl IntoElementKey for $ty {
87        fn into_element_key(self) -> String { self.to_string() }
88    })* };
89}
90integer_keys!(
91    u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize
92);
93
94#[doc(hidden)]
95#[derive(Debug, PartialEq, Eq)]
96pub struct Declaration {
97    pub family: &'static str,
98    pub keyed: bool,
99    pub package: &'static str,
100    pub version: &'static str,
101    pub file: &'static str,
102    pub line: u32,
103}
104/// Target-specific, normalized declaration. Provenance is omitted in release builds.
105#[derive(Clone, Debug, PartialEq, Eq)]
106pub struct RegisteredId {
107    pub family: String,
108    pub keyed: bool,
109    pub package: String,
110    pub version: String,
111    pub locations: Vec<String>,
112}
113#[cfg(not(target_arch = "wasm32"))]
114#[linkme::distributed_slice]
115#[doc(hidden)]
116pub static DECLARATIONS: [Declaration];
117
118/// Return the linked app's vocabulary, independent of visited pages. Reject conflicting
119/// shapes and owners; repeated declarations within one package are permitted.
120///
121/// # Errors
122///
123/// Returns a message when declarations of one family conflict in shape or owner or, on web,
124/// when the `day_ids` section was never handed off.
125pub fn registry() -> Result<&'static [RegisteredId], String> {
126    #[cfg(not(target_arch = "wasm32"))]
127    {
128        static CATALOG: std::sync::OnceLock<Result<Vec<RegisteredId>, String>> =
129            std::sync::OnceLock::new();
130        CATALOG
131            .get_or_init(|| {
132                normalize(
133                    DECLARATIONS
134                        .iter()
135                        .map(|d| RegisteredId {
136                            family: d.family.into(),
137                            keyed: d.keyed,
138                            package: d.package.into(),
139                            version: d.version.into(),
140                            locations: if d.file.is_empty() {
141                                vec![]
142                            } else {
143                                vec![format!("{}:{}", d.file, d.line)]
144                            },
145                        })
146                        .collect(),
147                )
148            })
149            .as_ref()
150            .map(Vec::as_slice)
151            .map_err(Clone::clone)
152    }
153    #[cfg(target_arch = "wasm32")]
154    WEB_REGISTRY
155        .get()
156        .ok_or("missing day_ids custom section handoff")?
157        .as_ref()
158        .map(Vec::as_slice)
159        .map_err(Clone::clone)
160}
161/// The exact family portion of a canonical locator; used only for mounted diagnostics.
162#[must_use]
163pub fn family_of(id: &str) -> &str {
164    let mut chars = id.char_indices().peekable();
165    while let Some((i, c)) = chars.next() {
166        if c == ':' {
167            if chars.peek().is_some_and(|(_, c)| *c == ':') {
168                chars.next();
169            } else {
170                return &id[..i];
171            }
172        }
173    }
174    id
175}
176
177fn normalize(records: Vec<RegisteredId>) -> Result<Vec<RegisteredId>, String> {
178    let mut catalog: BTreeMap<String, RegisteredId> = BTreeMap::new();
179    for record in records {
180        if let Some(prior) = catalog.get_mut(&record.family) {
181            if (prior.keyed, &prior.package, &prior.version)
182                != (record.keyed, &record.package, &record.version)
183            {
184                let owner = |r: &RegisteredId| {
185                    let shape = if r.keyed { "keyed" } else { "static" };
186                    match r.locations.first() {
187                        Some(at) => format!("{shape} in {} {} at {at}", r.package, r.version),
188                        None => format!("{shape} in {} {}", r.package, r.version),
189                    }
190                };
191                return Err(format!(
192                    "conflicting element ID declaration: {} ({}; {})",
193                    record.family,
194                    owner(prior),
195                    owner(&record)
196                ));
197            }
198            prior.locations.extend(record.locations);
199            prior.locations.sort();
200            prior.locations.dedup();
201        } else {
202            catalog.insert(record.family.clone(), record);
203        }
204    }
205    Ok(catalog.into_values().collect())
206}
207
208#[doc(hidden)]
209pub const fn validate_name(name: &str) {
210    let bytes = name.as_bytes();
211    assert!(!bytes.is_empty(), "element ID must not be empty");
212    let mut start = 0;
213    let mut i = 0;
214    while i <= bytes.len() {
215        if i == bytes.len() || bytes[i] == b':' {
216            assert!(i > start, "empty element ID namespace segment");
217            assert!(
218                bytes[start] >= b'a' && bytes[start] <= b'z',
219                "element ID must start with a lowercase ASCII letter"
220            );
221            assert!(
222                bytes[i - 1] != b'_',
223                "element ID must not end with underscore"
224            );
225            // Rust ident fragments accept keywords, including raw identifiers. Keep the
226            // protocol vocabulary independent of the edition used by the calling crate.
227            let keywords = [
228                "as",
229                "async",
230                "await",
231                "break",
232                "const",
233                "continue",
234                "crate",
235                "dyn",
236                "else",
237                "enum",
238                "extern",
239                "false",
240                "fn",
241                "for",
242                "if",
243                "impl",
244                "in",
245                "let",
246                "loop",
247                "match",
248                "mod",
249                "move",
250                "mut",
251                "pub",
252                "ref",
253                "return",
254                "self",
255                "static",
256                "struct",
257                "super",
258                "trait",
259                "true",
260                "type",
261                "unsafe",
262                "use",
263                "where",
264                "while",
265                "abstract",
266                "become",
267                "box",
268                "do",
269                "final",
270                "gen",
271                "macro",
272                "override",
273                "priv",
274                "try",
275                "typeof",
276                "unsized",
277                "virtual",
278                "yield",
279                "union",
280                "macro_rules",
281            ];
282            let mut k = 0;
283            while k < keywords.len() {
284                let keyword = keywords[k].as_bytes();
285                let mut equal = keyword.len() == i - start;
286                let mut j = 0;
287                while equal && j < keyword.len() {
288                    equal = bytes[start + j] == keyword[j];
289                    j += 1;
290                }
291                assert!(!equal, "Rust keyword is not an element ID");
292                k += 1;
293            }
294            if i == bytes.len() {
295                break;
296            }
297            assert!(
298                i + 1 < bytes.len() && bytes[i + 1] == b':',
299                "invalid namespace separator"
300            );
301            i += 2;
302            start = i;
303        } else {
304            let b = bytes[i];
305            assert!(
306                (b >= b'a' && b <= b'z') || (b >= b'0' && b <= b'9') || b == b'_',
307                "element IDs use lowercase ASCII snake_case, not raw identifiers"
308            );
309            assert!(
310                b != b'_' || i == start || bytes[i - 1] != b'_',
311                "double underscore in element ID"
312            );
313            i += 1;
314        }
315    }
316}
317
318/// Declare an ID at its piece, including a link-time catalog entry.
319///
320/// ```
321/// let save = day_core::id!(account::save);
322/// let row = day_core::id!(query_row, 42_u64);
323/// assert_eq!(save.as_str(), "account::save");
324/// assert_eq!(row.as_str(), "query_row:42");
325/// ```
326///
327/// Names are declarations using identifier tokens, with no string or case-conversion path.
328///
329/// ```compile_fail
330/// let _ = day_core::id!("save");
331/// ```
332/// ```compile_fail
333/// let _ = day_core::id!(Save);
334/// ```
335/// ```compile_fail
336/// let _ = day_core::id!(r#save);
337/// ```
338/// ```compile_fail
339/// let _ = day_core::id!(account__save);
340/// ```
341/// ```compile_fail
342/// let _ = day_core::id!(type);
343/// ```
344#[macro_export]
345macro_rules! id {
346    ($first:ident $(:: $rest:ident)* $(,)?) => {{
347        $crate::__declare_element_id!(false, "s", $first $(:: $rest)*);
348        $crate::ElementId::from_declaration(&__DAY_ID)
349    }};
350    ($first:ident $(:: $rest:ident)*, $key:expr $(,)?) => {{
351        $crate::__declare_element_id!(true, "k", $first $(:: $rest)*);
352        $crate::ElementId::with_key(&__DAY_ID, $key)
353    }};
354}
355#[doc(hidden)]
356#[macro_export]
357macro_rules! __declare_element_id {
358    ($keyed:expr, $flag:literal, $first:ident $(:: $rest:ident)*) => {
359        const __NAME: &str = concat!(stringify!($first), $("::", stringify!($rest)),*);
360        const _: () = $crate::element_id::validate_name(__NAME);
361        #[cfg(not(target_arch = "wasm32"))]
362        #[$crate::linkme::distributed_slice($crate::element_id::DECLARATIONS)]
363        #[linkme(crate = $crate::linkme)]
364        static __DAY_ID: $crate::element_id::Declaration = $crate::element_id::Declaration {
365            family: __NAME, keyed: $keyed, package: env!("CARGO_PKG_NAME"), version: env!("CARGO_PKG_VERSION"),
366            file: if cfg!(debug_assertions) { file!() } else { "" },
367            line: if cfg!(debug_assertions) { line!() } else { 0 },
368        };
369        #[cfg(target_arch = "wasm32")]
370        static __DAY_ID: $crate::element_id::Declaration = $crate::element_id::Declaration {
371            family: __NAME, keyed: $keyed, package: env!("CARGO_PKG_NAME"), version: env!("CARGO_PKG_VERSION"), file: "", line: 0,
372        };
373        #[cfg(target_arch = "wasm32")]
374        const __PAYLOAD: &str = concat!("D1\0", $flag, "\0", stringify!($first), $("::", stringify!($rest),)* "\0", env!("CARGO_PKG_NAME"), "\0", env!("CARGO_PKG_VERSION"));
375        #[cfg(target_arch = "wasm32")]
376        #[$crate::__retain_element_id]
377        #[used]
378        #[unsafe(link_section = "day_ids")]
379        static __DAY_ID_BYTES: [u8; __PAYLOAD.len()+4] = $crate::element_id::record_bytes(__PAYLOAD);
380    };
381}
382
383#[doc(hidden)]
384#[must_use]
385pub const fn record_bytes<const N: usize>(payload: &str) -> [u8; N] {
386    let mut out = [0; N];
387    let length = (payload.len() as u32).to_le_bytes();
388    let mut i = 0;
389    while i < 4 {
390        out[i] = length[i];
391        i += 1;
392    }
393    i = 0;
394    while i < payload.len() {
395        out[i + 4] = payload.as_bytes()[i];
396        i += 1;
397    }
398    out
399}
400#[cfg(target_arch = "wasm32")]
401#[crate::__retain_element_id]
402#[used]
403#[unsafe(link_section = "day_ids")]
404static SENTINEL: [u8; 6] = record_bytes("D1");
405#[cfg(target_arch = "wasm32")]
406static WEB_REGISTRY: std::sync::OnceLock<Result<Vec<RegisteredId>, String>> =
407    std::sync::OnceLock::new();
408/// Install all concatenated custom sections once, before app startup. Invalid metadata
409/// remains an error at the protocol boundary; it never becomes an empty catalog.
410///
411/// # Errors
412///
413/// Returns a message when a registry is already installed.
414#[cfg(target_arch = "wasm32")]
415pub fn install_web_registry(bytes: &[u8]) -> Result<(), String> {
416    WEB_REGISTRY
417        .set(decode_records(bytes))
418        .map_err(|_| "element registry already installed".to_owned())
419}
420#[cfg(any(test, target_arch = "wasm32"))]
421fn decode_records(mut bytes: &[u8]) -> Result<Vec<RegisteredId>, String> {
422    let mut records = Vec::new();
423    let mut sentinel = false;
424    while !bytes.is_empty() {
425        let length = bytes.get(..4).ok_or("truncated day_ids length")?;
426        let length = u32::from_le_bytes(length.try_into().unwrap()) as usize;
427        bytes = &bytes[4..];
428        let payload = bytes.get(..length).ok_or("truncated day_ids record")?;
429        bytes = &bytes[length..];
430        let text = std::str::from_utf8(payload).map_err(|_| "non UTF-8 day_ids record")?;
431        if text == "D1" {
432            sentinel = true;
433            continue;
434        }
435        let fields: Vec<_> = text.split('\0').collect();
436        if fields.len() != 5
437            || fields[0] != "D1"
438            || !matches!(fields[1], "s" | "k")
439            || fields[2].is_empty()
440        {
441            return Err("invalid day_ids schema/record".into());
442        }
443        records.push(RegisteredId {
444            family: fields[2].into(),
445            keyed: fields[1] == "k",
446            package: fields[3].into(),
447            version: fields[4].into(),
448            locations: vec![],
449        });
450    }
451    if !sentinel {
452        return Err("missing day_ids registry sentinel".into());
453    }
454    normalize(records)
455}
456
457#[cfg(test)]
458mod tests {
459    use super::*;
460    #[test]
461    fn exact_names_and_injective_keys() {
462        assert_eq!(crate::id!(identity), crate::id!(identity));
463        assert_eq!(crate::id!(account::save).as_str(), "account::save");
464        assert_eq!(
465            crate::id!(query_row, ":% café").as_str(),
466            "query_row:%3A%25%20caf%C3%A9"
467        );
468        assert_eq!(
469            crate::id!(query_row, 42).as_str(),
470            crate::id!(query_row, "42").as_str()
471        );
472        let calls = std::cell::Cell::new(0);
473        let _ = crate::id!(once, {
474            calls.set(calls.get() + 1);
475            3
476        });
477        assert_eq!(calls.get(), 1);
478    }
479    #[allow(dead_code)]
480    fn unused<T>(_: Option<T>) {
481        let _ = crate::id!(never_mounted);
482    }
483    #[test]
484    fn registry_includes_unused_generic() {
485        assert!(
486            registry()
487                .unwrap()
488                .iter()
489                .any(|d| d.family == "never_mounted")
490        );
491    }
492    #[test]
493    fn framed_metadata_and_fail_closed() {
494        let mut data = record_bytes::<6>("D1").to_vec();
495        let payload = concat!("D1\0k\0row\0app\0", "1");
496        data.extend_from_slice(&(payload.len() as u32).to_le_bytes());
497        data.extend_from_slice(payload.as_bytes());
498        assert_eq!(decode_records(&data).unwrap()[0].family, "row");
499        assert!(decode_records(&data[6..]).is_err());
500        assert!(decode_records(&data[..data.len() - 1]).is_err());
501    }
502    #[test]
503    fn normalization_rejects_owner_and_shape_conflicts() {
504        let record = RegisteredId {
505            family: "save".into(),
506            keyed: false,
507            package: "fixture".into(),
508            version: "1".into(),
509            locations: vec!["fixture.rs:1".into()],
510        };
511        let mut duplicate = record.clone();
512        duplicate.locations = vec!["fixture.rs:2".into()];
513        let normalized = normalize(vec![record.clone(), duplicate.clone()]).unwrap();
514        assert_eq!(normalized.len(), 1);
515        assert_eq!(normalized[0].locations.len(), 2);
516        duplicate.keyed = true;
517        assert!(normalize(vec![record.clone(), duplicate.clone()]).is_err());
518        duplicate.keyed = false;
519        duplicate.package = "other_fixture".into();
520        // The message names both owners, so a collision between two crates is traceable.
521        assert_eq!(
522            normalize(vec![record, duplicate]).unwrap_err(),
523            "conflicting element ID declaration: save (static in fixture 1 at fixture.rs:1; \
524             static in other_fixture 1 at fixture.rs:2)"
525        );
526    }
527}