sophia_api/ns/_macro.rs
1/// Create a "namespace module"
2/// defining a set of terms within a given IRI space.
3///
4/// # Tests
5/// This macro also create a test module to check that all created IRIs are valid.
6///
7/// This allows to skip those checks at runtime, keeping the initialization of the namespace fast.
8///
9/// # Example
10/// ```
11/// # #[macro_use] extern crate sophia_api;
12/// # use sophia_iri::IriRef;
13/// /// An example namespace module
14/// pub mod ex {
15/// namespace! {
16/// "http://example.org/ns#",
17/// Foo,
18/// Bar,
19/// Baz
20/// }
21/// }
22///
23/// assert_eq!(ex::Foo, IriRef::new_unchecked("http://example.org/ns#Foo"));
24/// assert_eq!(ex::Bar, IriRef::new_unchecked("http://example.org/ns#Bar"));
25/// ```
26#[macro_export]
27macro_rules! namespace {
28 ($iri_prefix:expr, $($suffix:ident),*; $($r_id:ident, $r_sf:expr),*) => {
29 /// Prefix used in this namespace.
30 pub static PREFIX: $crate::ns::IriRef<&'static str> = $crate::ns::IriRef::new_unchecked_const($iri_prefix);
31 $(
32 $crate::ns_iri!(PREFIX, $suffix);
33 )*
34 $(
35 $crate::ns_iri!(PREFIX, $r_id, $r_sf);
36 )*
37
38 /// Test module for checking tha IRIs are valid
39 #[cfg(test)]
40 mod test_valid_iri {
41 $(
42 #[allow(non_snake_case)]
43 #[test]
44 fn $suffix() {
45 let iri = $crate::ns::NsTerm::new_unchecked(
46 super::PREFIX,
47 stringify!($suffix),
48 );
49 assert!($crate::ns::IriRef::new(iri.to_string()).is_ok());
50 }
51 )*
52 $(
53 #[allow(non_snake_case)]
54 #[test]
55 fn $r_id() {
56 let iri = $crate::ns::NsTerm::new_unchecked(
57 super::PREFIX,
58 $r_sf,
59 );
60 assert!($crate::ns::IriRef::new(iri.to_string()).is_ok());
61 }
62 )*
63 }
64 };
65 ($iri_prefix:expr, $($suffix:ident),*) => {
66 namespace!($iri_prefix, $($suffix),*;);
67 };
68}
69
70/// Create a term in a "namespace module".
71/// In general, you should use the [`namespace!`](macro.namespace.html) macro instead.
72///
73/// # Safety
74/// This macro is conceptually unsafe,
75/// as it is never checked that the prefix IRI is a valid IRI reference.
76#[macro_export]
77macro_rules! ns_iri {
78 ($prefix:expr, $ident:ident) => {
79 $crate::ns_iri!($prefix, $ident, stringify!($ident));
80 };
81 ($prefix:expr, $ident:ident, $suffix:expr) => {
82 /// Generated term.
83 #[allow(non_upper_case_globals)]
84 pub static $ident: $crate::ns::NsTerm = $crate::ns::NsTerm::new_unchecked($prefix, $suffix);
85 };
86}