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
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
//! # IRI Enums
//!
//! <table><tr>
//! 	<td><a href="https://docs.rs/iref-enum">Documentation</a></td>
//! 	<td><a href="https://crates.io/crates/iref-enum">Crate informations</a></td>
//! 	<td><a href="https://github.com/timothee-haudebourg/iref-enum">Repository</a></td>
//! </tr></table>
//!
//! This is a companion crate for `iref` providing a derive macro to declare
//! enum types that converts into/from IRIs.
//!
//! Storage and comparison of IRIs can be costly. One may prefer the use of an enum
//! type representing known IRIs with cheap convertion functions between the two.
//! This crate provides a way to declare such enums in an simple way through the
//! use of a `IriEnum` derive macro.
//! This macro will implement `TryFrom<Iri>` and `Into<Iri>` for you.
//!
//! ## Basic usage
//!
//! Use `#[derive(IriEnum)]` attribute to generate the implementation of
//! `TryFrom<Iri>` and `Into<Iri>` for the enum type.
//! The IRI of each variant is defined with the `iri` attribute:
//! ```rust
//! # #![feature(proc_macro_hygiene)]
//! #[macro_use]
//! extern crate iref_enum;
//! use std::convert::TryInto;
//!
//! #[derive(IriEnum, PartialEq, Debug)]
//! pub enum Vocab {
//! 	#[iri("http://xmlns.com/foaf/0.1/name")] Name,
//! 	#[iri("http://xmlns.com/foaf/0.1/knows")] Knows
//! }
//!
//! pub fn main() {
//! 	let term: Vocab = static_iref::iri!("http://xmlns.com/foaf/0.1/name").try_into().unwrap();
//! 	assert_eq!(term, Vocab::Name)
//! }
//! ```
//!
//! ## Compact IRIs
//!
//! The derive macro also support compact IRIs using the special `iri_prefix` attribute.
//! First declare a prefix associated to a given `IRI`.
//! Then any `iri` attribute of the form `prefix:suffix` we be expanded into the concatenation of the prefix IRI and `suffix`.
//!
//! ```rust
//! # #![feature(proc_macro_hygiene)]
//! # use::iref_enum::IriEnum;
//! #[derive(IriEnum)]
//! #[iri_prefix("foaf" = "http://xmlns.com/foaf/0.1/")]
//! pub enum Vocab {
//! 	#[iri("foaf:name")] Name,
//! 	#[iri("foaf:knows")] Knows
//! }
//! ```
extern crate proc_macro;

use proc_macro::TokenStream;
use proc_macro2::TokenTree;
use quote::quote;
use syn;
use std::collections::HashMap;
use iref::IriBuf;

macro_rules! error {
	( $( $x:expr ),* ) => {
		{
			let msg = format!($($x),*);
			let tokens: TokenStream = format!("compile_error!(\"{}\");", msg).parse().unwrap();
			tokens
		}
	};
}

fn filter_attribute(attr: syn::Attribute, name: &str) -> Result<Option<proc_macro2::TokenStream>, TokenStream> {
	if let Some(attr_id) = attr.path.get_ident() {
		if attr_id == name {
			if let Some(TokenTree::Group(group)) = attr.tokens.into_iter().next() {
				Ok(Some(group.stream()))
			} else {
				return Err(error!("malformed `{}` attribute", name))
			}
		} else {
			Ok(None)
		}
	} else {
		Ok(None)
	}
}

fn expand_iri(value: &str, prefixes: &HashMap<String, IriBuf>) -> Result<IriBuf, ()> {
	if let Some(index) = value.find(':') {
		if index > 0 {
			let (prefix, suffix) = value.split_at(index);
			let suffix = &suffix[1..suffix.len()];

			if !suffix.starts_with("//") {
				if let Some(base_iri) = prefixes.get(prefix) {
					let concat = base_iri.as_str().to_string() + suffix;
					if let Ok(iri) = IriBuf::new(concat.as_str()) {
						return Ok(iri)
					} else {
						return Err(())
					}
				}
			}
		}
	}

	if let Ok(iri) = IriBuf::new(value) {
		Ok(iri)
	} else {
		Err(())
	}
}

#[proc_macro_derive(IriEnum, attributes(iri_prefix, iri))]
pub fn iri_enum_derive(input: TokenStream) -> TokenStream {
	let ast: syn::DeriveInput = syn::parse(input).unwrap();

	let mut prefixes = HashMap::new();
	for attr in ast.attrs {
		match filter_attribute(attr, "iri_prefix") {
			Ok(Some(tokens)) => {
				let mut tokens = tokens.into_iter();
				if let Some(token) = tokens.next() {
					if let Ok(prefix) = string_literal_token(token) {
						if let Some(_) = tokens.next() {
							if let Some(token) = tokens.next() {
								if let Ok(iri) = string_literal_token(token) {
									if let Ok(iri) = IriBuf::new(iri.as_str()) {
										prefixes.insert(prefix, iri);
									} else {
										return error!("invalid IRI `{}` for prefix `{}`", iri, prefix)
									}
								} else {
									return error!("expected a string literal")
								}
							} else {
								return error!("expected a string literal")
							}
						} else {
							return error!("expected `=` literal")
						}
					} else {
						return error!("expected a string literal")
					}
				} else {
					return error!("expected a string literal")
				}
			},
			Ok(None) => (),
			Err(tokens) => return tokens
		}
	}

	match ast.data {
		syn::Data::Enum(e) => {
			let type_id = ast.ident;
			let mut try_from = proc_macro2::TokenStream::new();
			let mut into = proc_macro2::TokenStream::new();

			for variant in e.variants {
				let variant_ident = variant.ident;
				let mut variant_iri: Option<IriBuf> = None;

				for attr in variant.attrs {
					match filter_attribute(attr, "iri") {
						Ok(Some(tokens)) => {
							match string_literal(tokens) {
								Ok(str) => {
									if let Ok(iri) = expand_iri(str.as_str(), &prefixes) {
										variant_iri = Some(iri)
									} else {
										return error!("invalid IRI `{}` for variant `{}`", str, variant_ident)
									}
								},
								Err(_) => {
									return error!("malformed `iri` attribute")
								}
							}
						},
						Ok(None) => (),
						Err(tokens) => return tokens
					}
				}

				if let Some(iri) = variant_iri {
					let iri = iri.as_str();

					try_from.extend(quote! {
						_ if iri == static_iref::iri!(#iri) => Ok(#type_id::#variant_ident),
					});

					into.extend(quote! {
						#type_id::#variant_ident => static_iref::iri!(#iri),
					});
				} else {
					return error!("missing IRI for enum variant `{}`", variant_ident)
				}
			}

			let output = quote! {
				impl ::std::convert::TryFrom<::iref::Iri<'_>> for #type_id {
					type Error = ();

					#[inline]
					fn try_from(iri: ::iref::Iri) -> ::std::result::Result<#type_id, ()> {
						match iri {
							#try_from
							_ => Err(())
						}
					}
				}

				impl<'a> From<&'a #type_id> for ::iref::Iri<'static> {
					#[inline]
					fn from(vocab: &'a #type_id) -> ::iref::Iri<'static> {
						match vocab {
							#into
						}
					}
				}

				impl From<#type_id> for ::iref::Iri<'static> {
					#[inline]
					fn from(vocab: #type_id) -> ::iref::Iri<'static> {
						match vocab {
							#into
						}
					}
				}

				impl iref::AsIri for #type_id {
					#[inline]
					fn as_iri(&self) -> ::iref::Iri {
						::iref::Iri::from(self)
					}
				}

				impl iref::AsIriRef for #type_id {
					#[inline]
					fn as_iri_ref(&self) -> ::iref::IriRef {
						::iref::Iri::from(self).into()
					}
				}
			};

			output.into()
		},
		_ => {
			error!("only enums are handled by IriEnum")
		}
	}
}

fn string_literal(tokens: proc_macro2::TokenStream) -> Result<String, &'static str> {
	if let Some(token) = tokens.into_iter().next() {
		string_literal_token(token)
	} else {
		return Err("expected one string parameter");
	}
}

fn string_literal_token(token: proc_macro2::TokenTree) -> Result<String, &'static str> {
	if let TokenTree::Literal(lit) = token {
		let str = lit.to_string();

		if str.len() >= 2 {
			let mut buffer = String::with_capacity(str.len()-2);
			for (i, c) in str.chars().enumerate() {
				if i == 0 || i == str.len()-1 {
					if c != '"' {
						return Err("expected string literal");
					}
				} else {
					buffer.push(c)
				}
			}

			Ok(buffer)
		} else {
			return Err("expected string literal");
		}
	} else {
		return Err("expected string literal");
	}
}