1 /**
2 *   Copyright: © 2012-2014 Anton Gushcha
3 *   License: Subject to the terms of the MIT license, as written in the included LICENSE file.
4 *   Authors:  NCrashed <ncrashed@gmail.com>,
5 *             LeMarwin <lemarwin42@gmail.com>,
6 *             Nazgull09 <nazgull90@gmail.com>
7 */
8 module devol.operatormng;
9 
10 import std.stdio;
11 import std.random;
12 import std.array;
13 
14 import devol.singleton;
15 
16 public
17 {
18 	import devol.operator;
19 	import devol.type;
20 }
21 
22 class OperatorMng : Singleton!OperatorMng
23 {
24 	static this()
25 	{
26 		new OperatorMng();
27 	}
28 	
29 	void registerOperator(T)()
30 		if ( __traits(compiles, "Operator t = new T()" ) )
31 	{
32 		Operator t = new T();
33 		
34 		if ( t.name in operators )
35 			throw new Exception("This operator already registered!");
36 		
37 		operators[t.name] = t;		
38 	}
39 	
40 	Operator getOperator(string name)
41 	{
42 		if ( name !in operators )
43 			throw new Exception("This operator isn't registered!");
44 			
45 		return operators[name];
46 	}
47 	
48 	Operator getRndOperator()
49 	{
50 		if (operators.keys.empty) return null;
51 		
52 		return operators.values[uniform(0,operators.length)];
53 	}
54 
55 	Operator getRndOperator(Type retType)
56 	{
57 		if (operators.keys.empty || retType is null) return null;
58 		
59 		auto buff = new Operator[0];
60 		
61 		foreach(op; operators)
62 		{
63 			if ( retType.isConvertable(op.rtype) )
64 				buff ~= op;
65 		}
66 		if (buff.empty) return null;
67 		
68 		return buff[uniform(0,buff.length)];
69 	}
70 	
71 	@property string[] strings()
72 	{
73 		auto ret = new string[0];
74 		foreach(s; operators.keys)
75 		{
76 			ret ~= s;
77 		}
78 		return ret;
79 	}
80 	
81 	protected Operator[string] operators;
82 }