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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
use config_element::{ConfigElement, Value, Table, Array};
use slr_parser::{Error, ErrorKind, Source};
use std::str::FromStr;
use std::default::Default;

/// Describes a way to convert a type to a ConfigElement and back.
pub trait ElementRepr<'l>
{
	/// Updates the contents of `self` based on values in the element.
	fn from_element(&mut self, elem: &ConfigElement, src: Option<&Source<'l>>) -> Result<(), Vec<Error>>;
	/// Creates an element that represents the contents of `self`.
	fn to_element(&self) -> ConfigElement;
}

macro_rules! element_repr_via_str_impl
{
	($t: ty) =>
	{
		impl<'l> $crate::ElementRepr<'l> for $t
		{
			fn from_element(&mut self, elem: &$crate::ConfigElement, src: Option<&$crate::Source<'l>>) -> Result<(), Vec<$crate::Error>>
			{
				match *elem.kind()
				{
					$crate::Value(ref val) =>
					{
						match <$t as FromStr>::from_str(&val)
						{
							Ok(v) =>
							{
								*self = v;
								Ok(())
							}
							Err(_) => Err(vec![$crate::Error::from_span::<()>(elem.span(), src, $crate::ErrorKind::InvalidRepr, &format!("Cannot parse '{}' as {}", val, stringify!($t)))])
						}
					},
					$crate::Table(_) => Err(vec![$crate::Error::from_span::<()>(elem.span(), src, $crate::ErrorKind::InvalidRepr, &format!("Cannot parse a table as {}", stringify!($t)))]),
					$crate::Array(_) => Err(vec![$crate::Error::from_span::<()>(elem.span(), src, $crate::ErrorKind::InvalidRepr, &format!("Cannot parse an array as {}", stringify!($t)))]),
				}
			}

			fn to_element(&self) -> ConfigElement
			{
				ConfigElement::new_value(self.to_string())
			}
		}
	}
}

element_repr_via_str_impl!(i8);
element_repr_via_str_impl!(i16);
element_repr_via_str_impl!(i32);
element_repr_via_str_impl!(isize);
element_repr_via_str_impl!(u8);
element_repr_via_str_impl!(u16);
element_repr_via_str_impl!(u32);
element_repr_via_str_impl!(usize);
element_repr_via_str_impl!(f32);
element_repr_via_str_impl!(f64);
element_repr_via_str_impl!(String);
element_repr_via_str_impl!(bool);

impl<'l, T: ElementRepr<'l> + Default> ElementRepr<'l> for Vec<T>
{
	fn from_element(&mut self, elem: &ConfigElement, src: Option<&Source<'l>>) -> Result<(), Vec<Error>>
	{
		match *elem.kind()
		{
			Array(ref arr) =>
			{
				let mut errors = vec![];
				self.clear();
				self.reserve(arr.len());
				for val_elem in arr
				{
					let mut val: T = Default::default();
					val.from_element(val_elem, src).map_err(|new_errors| errors.extend(new_errors)).ok();
					self.push(val);
				}
				if errors.is_empty()
				{
					Ok(())
				}
				else
				{
					Err(errors)
				}
			},
			Table(_) => Err(vec![Error::from_span::<()>(elem.span(), src, ErrorKind::InvalidRepr, "Cannot parse a table as 'Vec<T>'")]),
			Value(_) => Err(vec![Error::from_span::<()>(elem.span(), src, ErrorKind::InvalidRepr, "Cannot parse a value as 'Vec<T>'")]),
		}
	}

	fn to_element(&self) -> ConfigElement
	{
		let mut ret = ConfigElement::new_array();
		{
			let arr = ret.as_array_mut().unwrap();
			arr.reserve(self.len());
			for v in self
			{
				arr.push(v.to_element());
			}
		}
		ret
	}
}

#[macro_export]
#[doc(hidden)]
macro_rules! slr_def_struct_impl
{
	(
		struct $name: ident
		{
			$($field_name: ident : $field_type: ty = $field_init: expr),*
		}
	) =>
	{
		impl<'l> $crate::ElementRepr<'l> for $name
		{
			fn from_element(&mut self, elem: &$crate::ConfigElement, src: Option<&$crate::Source<'l>>) -> Result<(), Vec<$crate::Error>>
			{
				match *elem.kind()
				{
					$crate::Table(ref table) =>
					{
						let mut errors = vec![];
						for (k, v) in table
						{
							match &k[..]
							{
								$(
									stringify!($field_name) =>
									{
										// Use UFCS for a better error message.
										<$field_type as $crate::ElementRepr>::from_element(&mut self.$field_name, v, src).map_err(|new_errors| errors.extend(new_errors)).ok();
									},
								)*
								_ => errors.push($crate::Error::from_span::<()>(elem.span(), src, $crate::ErrorKind::UnknownField,
									&format!("{} does not have a field named {}", stringify!($name), k)))
							}
						}
						if errors.is_empty()
						{
							Ok(())
						}
						else
						{
							Err(errors)
						}
					},
					$crate::Value(_) => Err(vec![$crate::Error::from_span::<()>(elem.span(), src, $crate::ErrorKind::InvalidRepr, &format!("Cannot parse a value as {}", stringify!($name)))]),
					$crate::Array(_) => Err(vec![$crate::Error::from_span::<()>(elem.span(), src, $crate::ErrorKind::InvalidRepr, &format!("Cannot parse an array as {}", stringify!($name)))]),
				}
			}

			fn to_element(&self) -> $crate::ConfigElement
			{
				let mut ret = $crate::ConfigElement::new_table();
				{
					let tab = ret.as_table_mut().unwrap();
					$(
						tab.insert(stringify!($field_name).to_string(), <$field_type as $crate::ElementRepr>::to_element(&self.$field_name));
					)*
				}
				ret
			}
		}
	}
}

#[macro_export]
#[doc(hidden)]
macro_rules! slr_def_enum_impl
{
	(
		enum $name: ident
		{
			$($var_name: ident),*
		}
	) =>
	{
		impl<'l> $crate::ElementRepr<'l> for $name
		{
			fn from_element(&mut self, elem: &$crate::ConfigElement, src: Option<&$crate::Source<'l>>) -> Result<(), Vec<$crate::Error>>
			{
				match *elem.kind()
				{
					$crate::Value(ref val) =>
					{
						match &val[..]
						{
							$(
								stringify!($var_name) => 
								{
									*self = $name::$var_name;
									Ok(())
								}
								,
							)*
							_ => Err(vec![$crate::Error::from_span::<()>(elem.span(), src, $crate::ErrorKind::InvalidRepr, &format!("{} has no variant named '{}'", stringify!($name), val))])
						}
					},
					$crate::Table(_) => Err(vec![$crate::Error::from_span::<()>(elem.span(), src, $crate::ErrorKind::InvalidRepr, &format!("Cannot parse a table as {}", stringify!($name)))]),
					$crate::Array(_) => Err(vec![$crate::Error::from_span::<()>(elem.span(), src, $crate::ErrorKind::InvalidRepr, &format!("Cannot parse an array as {}", stringify!($name)))]),
				}
			}

			fn to_element(&self) -> $crate::ConfigElement
			{
				match *self
				{
					$(
						$name::$var_name => $crate::ConfigElement::new_value(stringify!($var_name).to_string()),
					)*
				}
			}
		}
	}
}

/** A macro to define the compile-time schemas for configuration elements.
You can use this macro to define structs and enums, like so:

~~~
#[macro_use]
extern crate slr_config;

slr_def!
{
	#[derive(Clone)] // Attributes supported.
	pub struct TestSchema
	{
		pub key: u32 = 0, // The rhs assignments are initializer expressions.
		pub arr: Vec<u32> = vec![]
	}
}

slr_def!
{
	pub enum TestEnum
	{
		VariantA,
		VariantB
	}
}

# fn main() {}
~~~

The types declared by both invocations implement `ElementRepr`, and the struct
versions also implement a `new` constructor which creates the type with the
default value specified by the macro invocation.
*/
#[macro_export]
macro_rules! slr_def
{
	(
		$(#[$attrs:meta])*
		pub struct $name: ident
		{
			$(pub $field_name: ident : $field_type: ty = $field_init: expr),* $(,)*
		}
	) =>
	{
		$(#[$attrs])*
		pub struct $name
		{
			$(pub $field_name : $field_type),*
		}

		impl $name
		{
			pub fn new() -> $name
			{
				$name
				{
					$($field_name: $field_init),*
				}
			}
		}

		slr_def_struct_impl!
		{
			struct $name
			{
				$($field_name : $field_type = $field_init),*
			}
		}
	};

	(
		$(#[$attrs:meta])*
		struct $name: ident
		{
			$($field_name: ident : $field_type: ty = $field_init: expr),* $(,)*
		}
	) =>
	{
		$(#[$attrs])*
		struct $name
		{
			$($field_name : $field_type),*
		}

		impl $name
		{
			fn new() -> $name
			{
				$name
				{
					$($field_name: $field_init),*
				}
			}
		}

		slr_def_struct_impl!
		{
			struct $name
			{
				$($field_name : $field_type = $field_init),*
			}
		}
	};

	(
		$(#[$attrs:meta])*
		enum $name: ident
		{
			$($var_name: ident),* $(,)*
		}
	) =>
	{
		$(#[$attrs])*
		enum $name
		{
			$($var_name),*
		}

		slr_def_enum_impl!
		{
			enum $name
			{
				$($var_name),*
			}
		}
	};

	(
		$(#[$attrs:meta])*
		pub enum $name: ident
		{
			$($var_name: ident),* $(,)*
		}
	) =>
	{
		$(#[$attrs])*
		pub enum $name
		{
			$($var_name),*
		}

		slr_def_enum_impl!
		{
			enum $name
			{
				$($var_name),*
			}
		}
	};
}