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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
/*!
Let us use an example to see how cvars might be implemented for it.

```
extern crate cvar;

use ::std::cell::{Cell, RefCell};

struct Foo {
	int: Cell<i32>,
	name: RefCell<String>,
}
impl Foo {
	fn greet(&self, ctx: &mut cvar::Context) -> cvar::BoxResult<()> {
		Ok(try!(writeln!(ctx.write, "Hello, {}!", *self.name.borrow())))
	}
}
```

Important is that this library is designed with passing non-mutable references around, thus configurable variables need interior mutability.

That is the basic setup, we would like to create these properties:

* `foo.int`: Property representing an `i32` variable.

* `foo.name`: The name used in the greeting.

* `foo.greet!`: An action that will print a greeting for `foo.name`. See the [`OnInvoke`](trait.OnInvoke.html) trait for more information about its parameters.

```
# use ::std::cell::{Cell, RefCell}; struct Foo { int: Cell<i32>, name: RefCell<String>, } impl Foo { fn greet(&self, ctx: &mut cvar::Context) -> cvar::BoxResult<()> { Ok(try!(writeln!(ctx.write, "Hello, {}!", *self.name.borrow()))) } }
impl cvar::IVisit for Foo {
	fn visit(&self, f: &mut FnMut(cvar::Node)) {
		use cvar::{Property, Action};
		f(From::from(&Property::new("int", "int description", &self.int, 42)));
		f(From::from(&Property::new("name", "name description", &self.name, "Casper")));
		f(From::from(&Action::new("greet!", "action description", |ctx| self.greet(ctx))));
	}
}
```

Accessing children is done via the [`IVisit`](trait.IVisit.html) trait implementing the Visitor Pattern. Its implementation will invoke the callback with every child as a [`Node`](enum.Node.html).

```
# use ::std::cell::{Cell, RefCell}; struct Foo { int: Cell<i32>, name: RefCell<String>, } impl Foo { fn greet(&self, ctx: &mut cvar::Context) -> cvar::BoxResult<()> { Ok(try!(writeln!(ctx.write, "Hello, {}!", *self.name.borrow()))) } }
# impl cvar::IVisit for Foo { fn visit(&self, f: &mut FnMut(cvar::Node)) { use cvar::{Property, Action}; f(From::from(&Property::new("int", "int description", &self.int, 42))); f(From::from(&Property::new("name", "name description", &self.name, "Casper"))); f(From::from(&Action::new("greet!", "action description", |ctx| self.greet(ctx)))); } }
struct Root {
	foo: Foo,
}
impl cvar::IVisit for Root {
	fn visit(&self, f: &mut FnMut(cvar::Node)) {
		use cvar::List;
		f(From::from(&List::new("foo", "foo description", &self.foo)));
	}
}
```

To access these cvars there is one thing missing: a root object from which they are reachable. Here modeled by having the root own a `Foo` instance.

An important note is that the root is not a list node, it does not have any metadata it just exists as a point where the rest of the cvars are accessible from.

```
# use ::std::cell::{Cell, RefCell}; struct Foo { int: Cell<i32>, name: RefCell<String>, } impl Foo { fn greet(&self, ctx: &mut cvar::Context) -> cvar::BoxResult<()> { Ok(try!(writeln!(ctx.write, "Hello, {}!", *self.name.borrow()))) } }
# impl cvar::IVisit for Foo { fn visit(&self, f: &mut FnMut(cvar::Node)) { use cvar::{Property, Action}; f(From::from(&Property::new("int", "int description", &self.int, 42))); f(From::from(&Property::new("name", "name description", &self.name, "Casper"))); f(From::from(&Action::new("greet!", "action description", |ctx| self.greet(ctx)))); } }
# struct Root { foo: Foo, } impl cvar::IVisit for Root { fn visit(&self, f: &mut FnMut(cvar::Node)) { use cvar::List; f(From::from(&List::new("foo", "foo description", &self.foo))); } }
let root = Root {
	foo: Foo {
		int: Cell::new(13),
		name: RefCell::new(String::new()),
	},
};
```

That's it! Now we are almost ready, let us create an instance of the root.

```
# use ::std::cell::{Cell, RefCell}; struct Foo { int: Cell<i32>, name: RefCell<String>, } impl Foo { fn greet(&self, ctx: &mut cvar::Context) -> cvar::BoxResult<()> { Ok(try!(writeln!(ctx.write, "Hello, {}!", *self.name.borrow()))) } }
# impl cvar::IVisit for Foo { fn visit(&self, f: &mut FnMut(cvar::Node)) { use cvar::{Property, Action}; f(From::from(&Property::new("int", "int description", &self.int, 42))); f(From::from(&Property::new("name", "name description", &self.name, "Casper"))); f(From::from(&Action::new("greet!", "action description", |ctx| self.greet(ctx)))); } }
# struct Root { foo: Foo, } impl cvar::IVisit for Root { fn visit(&self, f: &mut FnMut(cvar::Node)) { use cvar::List; f(From::from(&List::new("foo", "foo description", &self.foo))); } }
# let root = Root { foo: Foo { int: Cell::new(13), name: RefCell::new(String::new()), }, };
assert_eq!(cvar::console::get(&root, "foo.int").unwrap(), "13");

cvar::console::set(&root, "foo.int", "7").unwrap();
assert_eq!(root.foo.int.get(), 7);

cvar::console::reset(&root, "foo.name").unwrap();
assert_eq!(*root.foo.name.borrow(), "Casper");

let mut console = Vec::new();
cvar::console::invoke(&root, "foo.greet!", &mut cvar::Context::new("-o arg", &mut console)).unwrap();
assert_eq!(console, b"Hello, Casper!\n");
```

And use various console functions to interact with the resulting configuration.

See `examples/repl.rs` for a more complex example!
*/

#[cfg(test)]
#[macro_use]
extern crate matches;

use ::std::{io, fmt};
use ::std::str::FromStr;
use ::std::cell::{Cell, RefCell};
use ::std::string::ToString;
use ::std::borrow::Borrow;
use ::std::error::Error as StdError;

pub mod console;

//----------------------------------------------------------------

/// Identifiers are node names joined with a separator.
///
/// Eg. `foo.bar` is an identifier where `foo` and `bar` are names and the `.` is the separator.
///
/// Nodes are allowed to have the separator in their names, creating pseudo hierarchies. No implicit list nodes are created.
///
/// Note: The separator shall be a printable ascii character enforced by debug assert.
pub const JOINER: u8 = b'.';

/// Node interface.
pub trait INode {
	/// Returns the node name.
	fn name(&self) -> &str;
	/// Returns the node description.
	fn description(&self) -> &str;
}

/// Pass through dummy.
///
/// Implements default callbacks for `OnChange` and `OnInvoke`.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Pass;

//----------------------------------------------------------------

/// Result with boxed error.
pub type BoxResult<T> = Result<T, Box<StdError>>;

/// Contextless error.
#[derive(Debug)]
pub enum InnerError {
	/// Name not found error.
	///
	/// When traversing the cvar hierarhcy, a child by the name was not found.
	NameError,
	/// Node is not a list.
	///
	/// When traversing the cvar hierarchy, expected the child to implement `IList`.
	///
	/// This happens when an id is given (eg. `foo.prop.baz`) but `foo.prop` is not a list of cvars itself.
	ListError,
	/// Node is not a property.
	///
	/// When traversing the cvar hierarchy, expected the child to implement `IProperty`.
	///
	/// This happens when an id is given (eg. `foo.list`) to get or set its value but `foo.list` is not a property.
	PropError,
	/// Node is not an action.
	///
	/// When traversing the cvar hierarchy, expected the child to implement `IAction`.
	///
	/// This happens when an id is invoked (eg. `foo.bar`) but `foo.bar` is not an action.
	ActionError,
	/// Error parsing the value.
	ParseError(Box<StdError>),
	/// Error validating the value.
	ChangeError(Box<StdError>),
	/// Cannot modify the cvar.
	///
	/// The property is read-only and cannot be modified.
	ConstError,
	/// Error invoking the action.
	InvokeError(Box<StdError>),
}
impl fmt::Display for InnerError {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		try!(self.description().fmt(f));
		match *self {
			InnerError::ParseError(ref err) |
			InnerError::ChangeError(ref err) |
			InnerError::InvokeError(ref err) => {
				write!(f, ": {}", err)
			},
			_ => Ok(()),
		}
	}
}
impl StdError for InnerError {
	fn description(&self) -> &str {
		match *self {
			InnerError::NameError => "name not found",
			InnerError::PropError => "property expected",
			InnerError::ListError => "list expected",
			InnerError::ActionError => "action expected",
			InnerError::ParseError(_) => "parse error",
			InnerError::ChangeError(_) => "change error",
			InnerError::ConstError => "property is read-only",
			InnerError::InvokeError(_) => "invoke error",
		}
	}
	fn cause(&self) -> Option<&StdError> {
		match *self {
			InnerError::ParseError(ref err) |
			InnerError::ChangeError(ref err) |
			InnerError::InvokeError(ref err) => {
				Some(&**err)
			},
			_ => None,
		}
	}
}

/// Contextual error.
#[derive(Debug)]
pub struct Error<'a> {
	/// Identifier argument.
	pub id: &'a str,
	/// Specific node that triggered the error, this is a substring of `id`.
	pub name: &'a str,
	/// The actual error.
	pub inner: InnerError,
	_private: (),
}
impl<'a> Error<'a> {
	pub fn new(id: &'a str, name: &'a str, inner: InnerError) -> Error<'a> {
		Error {
			id: id,
			name: name,
			inner: inner,
			_private: (),
		}
	}
}
impl<'a> fmt::Display for Error<'a> {
	fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result {
		unimplemented!()
	}
}
impl<'a> StdError for Error<'a> {
	fn description(&self) -> &str {
		self.inner.description()
	}
	fn cause(&self) -> Option<&StdError> {
		self.inner.cause()
	}
}

//----------------------------------------------------------------

/// Property state.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum PropState {
	/// The property has its default value set.
	Default,
	/// The property has a non-default value.
	UserSet,
	/// The value is not valid in the current context.
	Invalid,
}

/// Property node interface.
///
/// Provides an object safe interface for properties, type erasing its implementation.
pub trait IProperty: INode {
	/// Gets the value as a string.
	fn get(&self) -> String;
	/// Sets the value.
	///
	/// May fail with `InnerError::ParseError` if parsing the value yields an error.
	///
	/// May fail with `InnerError::ChangeError` if validating the value yields an error.
	fn set(&self, val: &str) -> Result<(), InnerError>;
	/// Resets the value to its default.
	fn reset(&self);
	/// Gets the default value as a string.
	fn default(&self) -> String;
	/// Returns the state of the property.
	fn state(&self) -> PropState;
}
impl<'a> fmt::Debug for &'a IProperty {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		f.debug_struct("Property")
			.field("name", &self.name())
			.field("desc", &self.description())
			.field("value", &self.get())
			.field("default", &self.default())
			.field("state", &self.state())
			.finish()
	}
}
impl<'a> From<&'a IProperty> for Node<'a> {
	fn from(prop: &'a IProperty) -> Node<'a> {
		Node::Prop(prop)
	}
}

//----------------------------------------------------------------

/// Abstraction over interior mutability.
pub trait Variable<T> where T: fmt::Debug {
	/// Gets a clone of the value.
	fn get(&self) -> T;
	/// Sets a new value.
	fn set(&self, val: T);
	/// Work with the value without a potentially expensive clone.
	fn with<R, F>(&self, f: F) -> R where F: FnOnce(&T) -> R;
}
impl<'a, T, V> Variable<T> for &'a V where T: fmt::Debug, V: Variable<T> {
	fn get(&self) -> T {
		Variable::get(*self)
	}
	fn set(&self, val: T) {
		Variable::set(*self, val)
	}
	fn with<R, F: FnOnce(&T) -> R>(&self, f: F) -> R {
		Variable::with(*self, f)
	}
}
impl<T> Variable<T> for Cell<T> where T: Copy + fmt::Debug {
	fn get(&self) -> T {
		Cell::get(self)
	}
	fn set(&self, val: T) {
		Cell::set(self, val)
	}
	fn with<R, F>(&self, f: F) -> R where F: FnOnce(&T) -> R {
		(f)(&Cell::get(self))
	}
}
impl<T> Variable<T> for RefCell<T> where T: Clone + fmt::Debug {
	fn get(&self) -> T {
		self.borrow().clone()
	}
	fn set(&self, val: T) {
		*self.borrow_mut() = val;
	}
	fn with<R, F>(&self, f: F) -> R where F: FnOnce(&T) -> R {
		(f)(&*self.borrow())
	}
}

//----------------------------------------------------------------

/// Accepted property value types.
///
/// Functionality is duplicated to allow custom implementations for external types, eg. `Option<T>`.
pub trait Value: Clone + PartialEq + fmt::Debug {
	fn parse(val: &str) -> BoxResult<Self>;
	fn to_string(&self) -> String;
}

/// Implement [`Value`](trait.Value.html) automatically for types that have appropriate `FromStr` and `ToString` implementations.
pub trait AutoValue: Copy + PartialEq + FromStr + ToString + fmt::Debug
	where Self::Err: 'static + StdError {}

impl AutoValue for i8 {}
impl AutoValue for i16 {}
impl AutoValue for i32 {}
impl AutoValue for i64 {}
impl AutoValue for isize {}
impl AutoValue for u8 {}
impl AutoValue for u16 {}
impl AutoValue for u32 {}
impl AutoValue for u64 {}
impl AutoValue for usize {}
impl AutoValue for f32 {}
impl AutoValue for f64 {}
impl AutoValue for bool {}

impl<T> Value for T
	where T: AutoValue,
	      T::Err: 'static + StdError
{
	fn parse(val: &str) -> BoxResult<Self> {
		Ok(try!(val.parse()))
	}
	fn to_string(&self) -> String {
		ToString::to_string(self)
	}
}

impl<T> Value for Option<T>
	where T: AutoValue,
	      T::Err: 'static + StdError
{
	fn parse(val: &str) -> BoxResult<Self> {
		if val == "None" {
			Ok(None)
		}
		else {
			Ok(Some(try!(val.parse())))
		}
	}
	fn to_string(&self) -> String {
		match *self {
			Some(ref val) => ToString::to_string(val),
			None => String::from("None"),
		}
	}
}

impl Value for String {
	fn parse(val: &str) -> BoxResult<String> {
		Ok(String::from(val))
	}
	fn to_string(&self) -> String {
		self.clone()
	}
}

//----------------------------------------------------------------

/// Property callback when its value is changed.
pub trait OnChange<T> {
	/// Given the old and assigned values produces the new value.
	///
	/// May return a validation error.
	fn change(&self, old: &T, val: T) -> BoxResult<T>;
}
impl<T> OnChange<T> for Pass {
	fn change(&self, _: &T, val: T) -> BoxResult<T> {
		Ok(val)
	}
}
impl<T, F> OnChange<T> for F where F: Fn(&T, T) -> BoxResult<T> {
	fn change(&self, old: &T, val: T) -> BoxResult<T> {
		(self)(old, val)
	}
}

//----------------------------------------------------------------

/// Property instance.
///
/// The `N`ame and `D`escription types allow abstracting over `&'static str`, `&'a str` and `String`. This supports dynamic cvars while only paying for what you need.
///
/// The `V`ariable type holds a [value](trait.Value.html) of the underlying `T`ype with interior mutability.
///
/// `F` is the callable type called when the value is changed.
pub struct Property<N, D, T, V, F>
	where N: Borrow<str>,
	      D: Borrow<str>,
	      T: Value,
	      V: Variable<T>,
	      F: OnChange<T>
{
	name: N,
	desc: D,
	var: V,
	def: T,
	change: F,
}
impl<N, D, T, V> Property<N, D, T, V, Pass> where N: Borrow<str>, D: Borrow<str>, T: Value, V: Variable<T> {
	/// Creates a new `Property`.
	///
	/// Given a name, description, [variable](trait.Variable.html) and default.
	///
	/// ```
	/// // The underlying data wrapped in a `Cell`.
	/// use std::cell::Cell;
	/// let var = Cell::new(13);
	///
	/// // The variable wrapped in a `Property`.
	/// use cvar::{Property, IProperty};
	/// let prop = Property::new("prop", "property description", &var, 42);
	/// assert_eq!(prop.get(), "13");
	/// prop.reset();
	/// assert_eq!(var.get(), 42);
	/// ```
	pub fn new<I>(name: N, desc: D, var: V, def: I) -> Property<N, D, T, V, Pass> where I: Into<T> {
		Property {
			name: name,
			desc: desc,
			var: var,
			def: def.into(),
			change: Pass,
		}
	}
}
impl<N, D, T, V> Property<N, D, T, V, Pass> where N: Borrow<str>, D: Borrow<str>, T: Value, V: Variable<T> {
	/// Creates a new `Property` with [change](trait.OnChange.html) callback.
	///
	/// Called when a new value is assigned to the property through the `set` and `reset` methods.
	/// It does not monitor the `V`older for changes.
	///
	/// The default value must always validate successfully or `reset` will panic.
	pub fn change<F>(self, change: F) -> Property<N, D, T, V, F> where F: Fn(&T, T) -> BoxResult<T> {
		debug_assert!(self.var.with(|old| (change)(old, self.def.clone()).is_ok()), "default value did not validate");
		Property {
			name: self.name,
			desc: self.desc,
			var: self.var,
			def: self.def,
			change: change,
		}
	}
}
impl<N, D, T, V, F> INode for Property<N, D, T, V, F> where N: Borrow<str>, D: Borrow<str>, T: Value, V: Variable<T>, F: OnChange<T> {
	fn name(&self) -> &str {
		self.name.borrow()
	}
	fn description(&self) -> &str {
		self.desc.borrow()
	}
}
impl<N, D, T, V, F> IProperty for Property<N, D, T, V, F> where N: Borrow<str>, D: Borrow<str>, T: Value, V: Variable<T>, F: OnChange<T> {
	fn get(&self) -> String {
		self.var.get().to_string()
	}
	fn set(&self, val: &str) -> Result<(), InnerError> {
		match Value::parse(val) {
			Ok(val) => {
				match self.var.with(|old| self.change.change(old, val)) {
					Ok(val) => self.var.set(val),
					Err(err) => return Err(InnerError::ChangeError(err)),
				}
			},
			Err(err) => return Err(InnerError::ParseError(err)),
		};
		Ok(())
	}
	fn reset(&self) {
		let val = self.var.with(|old| self.change.change(old, self.def.clone())).unwrap();
		self.var.set(val);
	}
	fn default(&self) -> String {
		self.def.to_string()
	}
	fn state(&self) -> PropState {
		match self.var.with(|val| val == &self.def) {
			true => PropState::Default,
			false => PropState::UserSet,
		}
	}
}
impl<'s, N, D, T, V, F> From<&'s Property<N, D, T, V, F>> for Node<'s> where N: Borrow<str>, D: Borrow<str>, T: Value, V: Variable<T>, F: OnChange<T> {
	fn from(prop: &'s Property<N, D, T, V, F>) -> Node<'s> {
		Node::Prop(prop)
	}
}

//----------------------------------------------------------------

/// Node interface.
#[derive(Copy, Clone)]
pub enum Node<'a> {
	Prop(&'a IProperty),
	List(&'a IList),
	Action(&'a IAction),
}
impl<'a> INode for Node<'a> {
	fn name(&self) -> &str {
		match *self {
			Node::Prop(prop) => prop.name(),
			Node::List(list) => list.name(),
			Node::Action(act) => act.name(),
		}
	}
	fn description(&self) -> &str {
		match *self {
			Node::Prop(prop) => prop.description(),
			Node::List(list) => list.description(),
			Node::Action(act) => act.description(),
		}
	}
}
impl<'a> fmt::Debug for Node<'a> {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		match *self {
			Node::Prop(prop) => {
				prop.fmt(f)
			},
			Node::List(list) => {
				list.fmt(f)
			},
			Node::Action(act) => {
				act.fmt(f)
			},
		}
	}
}

/// Visitor Pattern interface.
pub trait IVisit {
	/// Calls the callback `f` with every child casted as `Node`.
	///
	/// ```
	/// use ::std::cell::Cell;
	/// struct Object {
	/// 	foo: Cell<i32>,
	/// 	bar: Cell<i32>,
	/// }
	/// impl cvar::IVisit for Object {
	/// 	fn visit(&self, f: &mut FnMut(cvar::Node)) {
	/// 		use cvar::{Property};
	/// 		f(From::from(&Property::new("foo", "foo description", &self.foo, 42)));
	/// 		f(From::from(&Property::new("bar", "bar description", &self.bar, 12)));
	/// 	}
	/// }
	/// ```
	fn visit(&self, f: &mut FnMut(Node));
}
impl<'a> fmt::Debug for &'a IVisit {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		let mut f = f.debug_list();
		self.visit(&mut |node| {
			f.entry(&node);
		});
		f.finish()
	}
}

/// List node interface.
///
/// Provides an object safe interface for lists, type erasing its implementation.
pub trait IList: INode {
	/// Returns the visitor interface to access its children.
	fn as_visit(&self) -> &IVisit;
}
impl<'a> fmt::Debug for &'a IList {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		f.debug_struct("List")
			.field("name", &self.name())
			.field("desc", &self.description())
			.field("children", &self.as_visit())
			.finish()
	}
}
impl<'a> From<&'a IList> for Node<'a> {
	fn from(list: &'a IList) -> Node<'a> {
		Node::List(list)
	}
}

//----------------------------------------------------------------

/// List instance.
///
/// The `N`ame and `D`escription types allow abstracting over `&'static str`, `&'a str` and `String`. This supports dynamic cvars while only paying for what you need.
pub struct List<'a, N, D>
	where N: Borrow<str>,
	      D: Borrow<str>
{
	name: N,
	desc: D,
	visit: &'a IVisit,
}
impl<'a, N, D> List<'a, N, D> where N: Borrow<str>, D: Borrow<str> {
	/// Creates a new `List`.
	///
	/// Given a name, description and [visitor](trait.IVisit.html) to access its children.
	pub fn new(name: N, desc: D, visit: &'a IVisit) -> List<'a, N, D> {
		List {
			name: name,
			desc: desc,
			visit: visit,
		}
	}
}
impl<'a, N, D> INode for List<'a, N, D> where N: Borrow<str>, D: Borrow<str> {
	fn name(&self) -> &str {
		self.name.borrow()
	}
	fn description(&self) -> &str {
		self.desc.borrow()
	}
}
impl<'a, N, D> IList for List<'a, N, D> where N: Borrow<str>, D: Borrow<str> {
	fn as_visit(&self) -> &IVisit {
		self.visit
	}
}
impl<'s, 'a, N, D> From<&'s List<'a, N, D>> for Node<'s> where N: Borrow<str>, D: Borrow<str> {
	fn from(val: &'s List<'a, N, D>) -> Node<'s> {
		Node::List(val)
	}
}

//----------------------------------------------------------------

/// Invocation context.
///
/// Provides a place to pass parameters through to the action callback.
pub struct Context<'a> {
	/// The command arguments.
	///
	/// There are no extra constraints on the formatting, it is passed through to the underlying action.
	pub args: &'a str,
	/// A console-like interface.
	///
	/// Allows the action to let the world know what it has to say.
	pub write: &'a mut io::Write,
	_private: (),
}
impl<'a> Context<'a> {
	/// Constructs a new invocation context.
	pub fn new(args: &'a str, write: &'a mut io::Write) -> Context<'a> {
		Context {
			args: args,
			write: write,
			_private: (),
		}
	}
}

/// Action node interface.
///
/// Provides an object safe interface for actions, type erasing its implementation.
pub trait IAction: INode {
	/// Invoke the callback associated with the Action.
	fn invoke(&self, ctx: &mut Context) -> Result<(), InnerError>;
}
impl<'a> fmt::Debug for &'a IAction {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		f.debug_struct("Action")
			.field("name", &self.name())
			.field("desc", &self.description())
			.finish()
	}
}
impl<'a> From<&'a IAction> for Node<'a> {
	fn from(act: &'a IAction) -> Node<'a> {
		Node::Action(act)
	}
}

/// Action callback when invoked.
pub trait OnInvoke {
	fn invoke(&self, ctx: &mut Context) -> BoxResult<()>;
}
impl OnInvoke for Pass {
	fn invoke(&self, _: &mut Context) -> BoxResult<()> {
		Ok(())
	}
}
impl<F> OnInvoke for F where F: Fn(&mut Context) -> BoxResult<()> {
	fn invoke(&self, ctx: &mut Context) -> BoxResult<()> {
		(self)(ctx)
	}
}

//----------------------------------------------------------------

/// Action instance.
///
/// The `N`ame and `D`escription types allow abstracting over `&'static str`, `&'a str` and `String`. This supports dynamic cvars while only paying for what you need.
///
/// `F` is the callable type called when the action is invoked.
pub struct Action<N, D, F>
	where N: Borrow<str>,
	      D: Borrow<str>,
	      F: OnInvoke
{
	name: N,
	desc: D,
	f: F,
}
impl<N, D> Action<N, D, Pass> where N: Borrow<str>, D: Borrow<str> {
	/// Creates a new `Action`.
	///
	/// Given a name, description and a [callback](trait.OnInvoke.html) to be invoked.
	pub fn new<F>(name: N, desc: D, f: F) -> Action<N, D, F> where F: Fn(&mut Context) -> BoxResult<()> {
		Action {
			name: name,
			desc: desc,
			f: f,
		}
	}
}
impl<N, D, F> INode for Action<N, D, F> where N: Borrow<str>, D: Borrow<str>, F: OnInvoke {
	fn name(&self) -> &str {
		self.name.borrow()
	}
	fn description(&self) -> &str {
		self.desc.borrow()
	}
}
impl<N, D, F> IAction for Action<N, D, F> where N: Borrow<str>, D: Borrow<str>, F: OnInvoke {
	fn invoke(&self, ctx: &mut Context) -> Result<(), InnerError> {
		match self.f.invoke(ctx) {
			Ok(ok) => Ok(ok),
			Err(err) => Err(InnerError::InvokeError(err)),
		}
	}
}
impl<'s, N, D, F> From<&'s Action<N, D, F>> for Node<'s> where N: Borrow<str>, D: Borrow<str>, F: OnInvoke {
	fn from(val: &'s Action<N, D, F>) -> Node<'s> {
		Node::Action(val)
	}
}