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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
// Copyright (c) 2014 by SiegeLord
//
// All rights reserved. Distributed under LGPL 3.0. For full terms see the file LICENSE.

pub use self::ConfigElementKind::*;

use slr_parser::{parse_source, ConfigString, Error, ErrorKind, Printer, Source, Span, Visitor};
use std::collections::BTreeMap;
use std::fmt::{self, Display, Formatter};
use std::io;
use std::mem;
use std::path::Path;
use std::str::{from_utf8, FromStr};

/// A configuration element.
#[derive(Clone, Debug)]
pub struct ConfigElement
{
	kind: ConfigElementKind,
	span: Span,
}

// TODO: It's annoying that we lose the span information from Values and Table keys.
/// The kind of the configuration element.
#[derive(Clone, Debug)]
pub enum ConfigElementKind
{
	/// A simple value, containing a string.
	Value(String),
	/// A table, which is a mapping of strings to configuration elements.
	Table(BTreeMap<String, ConfigElement>),
	/// A tagged table, which is a mapping of strings to configuration elements
	/// with a string tag.
	TaggedTable(String, BTreeMap<String, ConfigElement>),
	/// An array of configuration elements.
	Array(Vec<ConfigElement>),
	/// An array of configuration elements with a string tag.
	TaggedArray(String, Vec<ConfigElement>),
}

impl ConfigElement
{
	/// Creates a new empty table.
	pub fn new_table() -> ConfigElement
	{
		ConfigElement {
			kind: Table(BTreeMap::new()),
			span: Span::new(),
		}
	}

	/// Creates a new empty tagged table.
	pub fn new_tagged_table(tag: String) -> ConfigElement
	{
		ConfigElement {
			kind: TaggedTable(tag, BTreeMap::new()),
			span: Span::new(),
		}
	}

	/// Creates a new value.
	pub fn new_value<T: ToString>(value: T) -> ConfigElement
	{
		ConfigElement {
			kind: Value(value.to_string()),
			span: Span::new(),
		}
	}

	/// Creates a new array.
	pub fn new_array() -> ConfigElement
	{
		ConfigElement {
			kind: Array(vec![]),
			span: Span::new(),
		}
	}

	/// Creates a new tagged array.
	pub fn new_tagged_array(tag: String) -> ConfigElement
	{
		ConfigElement {
			kind: TaggedArray(tag, vec![]),
			span: Span::new(),
		}
	}

	/// Parses a source and returns a table. The source will be reset by this
	/// operation, and must not be used with any spans created from a previous
	/// parsing done with that source.
	pub fn from_source<'l>(source: &mut Source<'l>) -> Result<ConfigElement, Error>
	{
		let mut root = ConfigElement::new_table();
		root.from_source_with_init(source)?;
		Ok(root)
	}

	/// Parses a source and returns a table.
	pub fn from_str(src: &str) -> Result<ConfigElement, Error>
	{
		ConfigElement::from_source(&mut Source::new(&Path::new("<anon>"), src))
	}

	/// Updates the elements in this table with new values parsed from source.
	/// If an error occurs, the contents of this table are undefined. The source
	/// will be reset by this operation, and must not be used with any spans
	/// created from a previous lexing done with that source.
	pub fn from_source_with_init<'l, 'm>(&mut self, source: &'m mut Source<'l>)
		-> Result<(), Error>
	{
		assert!(self.as_table().is_some());
		let mut root = ConfigElement::new_table();
		mem::swap(&mut root, self);
		let mut visitor = ConfigElementVisitor::new(root);
		parse_source(source, &mut visitor).map(|_| {
			mem::swap(&mut visitor.extract_root(), self);
		})
	}

	/// Updates the elements in this table with new values parsed from source.
	/// If an error occurs, the contents of this table are undefined.
	pub fn from_str_with_init(&mut self, src: &str) -> Result<(), Error>
	{
		self.from_source_with_init(&mut Source::new(&Path::new("<anon>"), src))
	}

	/// Returns the kind of this element.
	pub fn kind(&self) -> &ConfigElementKind
	{
		&self.kind
	}

	/// Returns the kind of this element.
	pub fn kind_mut(&mut self) -> &mut ConfigElementKind
	{
		&mut self.kind
	}

	/// Returns the span associated with this element.
	pub fn span(&self) -> Span
	{
		self.span
	}

	/// If this is a table, returns a pointer to its contents.
	pub fn as_table(&self) -> Option<&BTreeMap<String, ConfigElement>>
	{
		match self.kind
		{
			Table(ref table) | TaggedTable(_, ref table) => Some(table),
			_ => None,
		}
	}

	/// If this is a table, returns its contents.
	pub fn into_table(self) -> Option<BTreeMap<String, ConfigElement>>
	{
		match self.kind
		{
			Table(table) | TaggedTable(_, table) => Some(table),
			_ => None,
		}
	}

	/// If this is a table, returns a pointer to its contents.
	pub fn as_table_mut(&mut self) -> Option<&mut BTreeMap<String, ConfigElement>>
	{
		match self.kind
		{
			Table(ref mut table) | TaggedTable(_, ref mut table) => Some(table),
			_ => None,
		}
	}

	/// If this is a value, returns a pointer to its contents.
	pub fn as_value(&self) -> Option<&String>
	{
		match self.kind
		{
			Value(ref value) => Some(value),
			_ => None,
		}
	}

	/// If this is a value, returns its contents.
	pub fn into_value(self) -> Option<String>
	{
		match self.kind
		{
			Value(value) => Some(value),
			_ => None,
		}
	}

	/// If this is a value, returns a pointer to its contents.
	pub fn as_value_mut(&mut self) -> Option<&mut String>
	{
		match self.kind
		{
			Value(ref mut value) => Some(value),
			_ => None,
		}
	}

	/// If this is an array, returns a pointer to its contents.
	pub fn as_array(&self) -> Option<&Vec<ConfigElement>>
	{
		match self.kind
		{
			Array(ref array) | TaggedArray(_, ref array) => Some(array),
			_ => None,
		}
	}

	/// If this is an array, returns its contents.
	pub fn into_array(self) -> Option<Vec<ConfigElement>>
	{
		match self.kind
		{
			Array(array) | TaggedArray(_, array) => Some(array),
			_ => None,
		}
	}

	/// If this is an array, returns a pointer to its contents.
	pub fn as_array_mut(&mut self) -> Option<&mut Vec<ConfigElement>>
	{
		match self.kind
		{
			Array(ref mut array) | TaggedArray(_, ref mut array) => Some(array),
			_ => None,
		}
	}

	pub fn tag(&self) -> Option<&String>
	{
		match self.kind
		{
			TaggedTable(ref tag, _) | TaggedArray(ref tag, _) => Some(tag),
			_ => None,
		}
	}

	pub fn tag_mut(&mut self) -> Option<&mut String>
	{
		match self.kind
		{
			TaggedTable(ref mut tag, _) | TaggedArray(ref mut tag, _) => Some(tag),
			_ => None,
		}
	}

	/// Insert an element into a table or an array. Panics if self is a value.
	/// `name` is ignored if self is an array.
	pub fn insert<T: ToString>(&mut self, name: T, elem: ConfigElement)
	{
		match self.kind
		{
			Table(ref mut table) | TaggedTable(_, ref mut table) =>
			{
				table.insert(name.to_string(), elem);
			}
			Array(ref mut array) | TaggedArray(_, ref mut array) =>
			{
				array.push(elem);
			}
			_ => panic!("Trying to insert an element into a value!"),
		}
	}

	/// Outputs the string representation of this element into into a printer.
	pub fn print<W: io::Write>(
		&self, name: Option<&str>, is_root: bool, printer: &mut Printer<W>,
	) -> Result<(), io::Error>
	{
		match self.kind
		{
			Value(ref val) => printer.value(name, &val)?,
			Table(ref table) =>
			{
				printer.start_table(name, is_root, table.is_empty())?;
				for (k, v) in table
				{
					v.print(Some(k), false, printer)?;
				}
				printer.end_table(is_root)?;
			}
			TaggedTable(ref tag, ref table) =>
			{
				printer.start_tagged_table(name, tag, is_root, table.is_empty())?;
				for (k, v) in table
				{
					v.print(Some(k), false, printer)?;
				}
				printer.end_table(is_root)?;
			}
			Array(ref array) =>
			{
				let mut one_line = true;
				for v in array
				{
					match v.kind
					{
						Table(ref table) | TaggedTable(_, ref table) =>
						{
							if !table.is_empty()
							{
								one_line = false;
								break;
							}
						}
						_ => (),
					}
				}
				printer.start_array(name, one_line)?;
				for v in array
				{
					v.print(None, false, printer)?;
				}
				printer.end_array()?;
			}
			TaggedArray(ref tag, ref array) =>
			{
				let mut one_line = true;
				for v in array
				{
					match v.kind
					{
						Table(ref table) | TaggedTable(_, ref table) =>
						{
							if !table.is_empty()
							{
								one_line = false;
								break;
							}
						}
						_ => (),
					}
				}
				printer.start_tagged_array(name, tag, one_line)?;
				for v in array
				{
					v.print(None, false, printer)?;
				}
				printer.end_array()?;
			}
		}
		Ok(())
	}
}

impl Display for ConfigElement
{
	fn fmt(&self, formatter: &mut Formatter) -> Result<(), fmt::Error>
	{
		let mut buf = vec![];
		{
			let mut printer = Printer::new(&mut buf);
			self.print(None, true, &mut printer)
				.map_err(|_| fmt::Error)?;
		}
		write!(formatter, "{}", from_utf8(&buf).map_err(|_| fmt::Error)?)?;
		Ok(())
	}
}

fn visit_error<'l>(span: Span, source: &Source<'l>, msg: &str) -> Result<(), Error>
{
	Err(Error::from_span(
		span,
		Some(source),
		ErrorKind::ParseFailure,
		msg,
	))
}

struct ConfigElementVisitor
{
	// Name, element, initialized
	stack: Vec<(String, ConfigElement, bool)>,
}

impl ConfigElementVisitor
{
	fn new(root: ConfigElement) -> ConfigElementVisitor
	{
		ConfigElementVisitor {
			stack: vec![("root".to_string(), root, true)],
		}
	}

	fn extract_root(mut self) -> ConfigElement
	{
		assert!(self.stack.len() == 1);
		self.stack.pop().unwrap().1
	}
}

impl<'l> Visitor<'l> for ConfigElementVisitor
{
	fn start_element(&mut self, _src: &Source<'l>, name: ConfigString<'l>) -> Result<(), Error>
	{
		self.stack.push((
			name.to_string(),
			ConfigElement::new_value("".to_string()),
			false,
		));
		Ok(())
	}

	fn end_element(&mut self) -> Result<(), Error>
	{
		let stack_size = self.stack.len();
		if stack_size > 1
		{
			let (name, elem, _) = self.stack.pop().unwrap();
			self.stack[stack_size - 2].1.insert(name, elem);
		}
		Ok(())
	}

	fn append_string(&mut self, src: &Source<'l>, string: ConfigString<'l>) -> Result<(), Error>
	{
		let stack_size = self.stack.len();
		{
			let elem = &mut self.stack[stack_size - 1].1;
			elem.span.combine(string.span);
			match elem.kind
			{
				Value(ref mut val) => string.append_to_string(val),
				Table(_) =>
				{
					return visit_error(string.span, src, "Cannot append a string to a table")
				}
				TaggedTable(_, _) =>
				{
					return visit_error(
						string.span,
						src,
						"Cannot append a string to a tagged table",
					)
				}
				Array(_) =>
				{
					return visit_error(string.span, src, "Cannot append a string to an array")
				}
				TaggedArray(_, _) =>
				{
					return visit_error(
						string.span,
						src,
						"Cannot append a string to a tagged array",
					)
				}
			}
		}
		self.stack[stack_size - 1].2 = true;
		Ok(())
	}

	fn set_table(&mut self, _src: &Source<'l>, span: Span) -> Result<(), Error>
	{
		let stack_size = self.stack.len();
		self.stack[stack_size - 1].1 = ConfigElement::new_table();
		self.stack[stack_size - 1].1.span = span;
		self.stack[stack_size - 1].2 = true;
		Ok(())
	}

	fn set_tagged_table(
		&mut self, _src: &Source<'l>, span: Span, tag: ConfigString<'l>,
	) -> Result<(), Error>
	{
		let stack_size = self.stack.len();
		self.stack[stack_size - 1].1 = ConfigElement::new_tagged_table(tag.to_string());
		self.stack[stack_size - 1].1.span = span;
		self.stack[stack_size - 1].2 = true;
		Ok(())
	}

	fn set_array(&mut self, _src: &Source<'l>, span: Span) -> Result<(), Error>
	{
		let stack_size = self.stack.len();
		self.stack[stack_size - 1].1 = ConfigElement::new_array();
		self.stack[stack_size - 1].1.span = span;
		self.stack[stack_size - 1].2 = true;
		Ok(())
	}

	fn set_tagged_array(
		&mut self, _src: &Source<'l>, span: Span, tag: ConfigString<'l>,
	) -> Result<(), Error>
	{
		let stack_size = self.stack.len();
		self.stack[stack_size - 1].1 = ConfigElement::new_tagged_array(tag.to_string());
		self.stack[stack_size - 1].1.span = span;
		self.stack[stack_size - 1].2 = true;
		Ok(())
	}

	fn expand(&mut self, src: &Source<'l>, name: ConfigString<'l>) -> Result<(), Error>
	{
		let mut found_element = None;
		let span = name.span;
		let name = name.to_string();
		// Find the referenced element.
		for &(ref elem_name, ref elem, _) in self.stack.iter().rev()
		{
			// Can't insert currently modified element.
			if *elem_name == name
			{
				continue;
			}
			match elem.kind
			{
				Value(_) => continue,
				Table(ref table) | TaggedTable(_, ref table) =>
				{
					found_element = table.get(&name).map(|v| v.clone());
				}
				Array(ref array) | TaggedArray(_, ref array) =>
				{
					found_element = <usize>::from_str(&name)
						.ok()
						.and_then(|idx| array.get(idx))
						.map(|v| v.clone());
				}
			}
			if found_element.is_some()
			{
				break;
			}
		}

		if found_element.is_none()
		{
			return visit_error(
				span,
				src,
				&format!("Could not find an element named `{}`", name),
			);
		}
		let found_element = found_element.unwrap();

		let stack_size = self.stack.len();
		let lhs_is_initialized = self.stack[stack_size - 1].2;
		if lhs_is_initialized
		{
			match self.stack[stack_size - 1].1.kind
			{
				Value(ref mut lhs_val) => match found_element.kind
				{
					Value(ref found_val) => lhs_val.push_str(found_val),
					Table(_) => return visit_error(span, src, "Cannot append a table to a value"),
					TaggedTable(_, _) =>
					{
						return visit_error(span, src, "Cannot append a tagged table to a value")
					}
					Array(_) => return visit_error(span, src, "Cannot append an array to a value"),
					TaggedArray(_, _) =>
					{
						return visit_error(span, src, "Cannot append an tagged array to a value")
					}
				},
				Table(_) => return visit_error(span, src, "Cannot append to a table"),
				TaggedTable(_, _) =>
				{
					return visit_error(span, src, "Cannot append to a tagged table")
				}
				Array(_) => return visit_error(span, src, "Cannot append to an array"),
				TaggedArray(_, _) =>
				{
					return visit_error(span, src, "Cannot append to a tagged array")
				}
			}
		}
		else
		{
			self.stack[stack_size - 1].1 = found_element;
			self.stack[stack_size - 1].2 = true;
		}
		self.stack[stack_size - 1].1.span = span;
		Ok(())
	}
}