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