1 /**
2  * An implementation of Timon Gehr's X template
3  *
4  * License:
5  *   This Source Code Form is subject to the terms of
6  *   the Mozilla Public License, v. 2.0. If a copy of
7  *   the MPL was not distributed with this file, You
8  *   can obtain one at http://mozilla.org/MPL/2.0/.
9  *
10  * Authors:
11  *   Vladimir Panteleev <vladimir@thecybershadow.net>
12  */
13 
14 module ae.utils.meta.x;
15 
16 // Based on idea from Timon Gehr.
17 // http://forum.dlang.org/post/jdiu5s$13bo$1@digitalmars.com
18 
19 template X(string x)
20 {
21 	enum X = xImpl(x);
22 }
23 
24 private string xImpl(string x)
25 {
26 	string r;
27 
28 	for (size_t i=0; i<x.length; i++)
29 		if (x[i]=='@' && x[i+1]=='(')
30 		{
31 			auto j = i+2;
32 			for (int nest=1; nest; j++)
33 				nest += x[j] == '(' ? +1 : x[j] == ')' ? -1 : 0;
34 
35 			r ~= `"~(` ~ x[i+2..j-1] ~ `)~"`;
36 			i = j-1;
37 		}
38 		else
39 		{
40 			if (x[i]=='"' || x[i]=='\\')
41 				r ~= "\\";
42 			r ~= x[i];
43 		}
44 	return `"` ~ r ~ `"`;
45 }
46 
47 unittest
48 {
49 	enum VAR = "aoeu";
50 	int aoeu;
51 
52 	string INSTALL_MEANING_OF_LIFE(string TARGET)
53 	{
54 		return mixin(X!q{
55 			@(TARGET) = 42;
56 		});
57 	}
58 
59 	mixin(INSTALL_MEANING_OF_LIFE(VAR));
60 	assert(aoeu == 42);
61 }
62