-
Notifications
You must be signed in to change notification settings - Fork 0
/
metastrings.d
469 lines (416 loc) · 10.4 KB
/
metastrings.d
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
module xtk.metastrings;
//import std.algorithm : startsWith;
import std.ctype : isalpha, isalnum;
import std.traits : isCallable, isSomeString;
import std.typetuple : TypeTuple;
import std.conv : text;
/// ditto
template toStringNow(alias V)
{
static if (is(typeof(V)))
static if (__traits(compiles, { auto v = V; }))
alias V toStringNow;
else
enum toStringNow = V.stringof; // V is template
else static if (is(V))
enum toStringNow = V.stringof;
else
static assert(0, "undefined error with " ~ V.stringof);
}
/// ditto
template toStringNow(T)
{
enum toStringNow = T.stringof;
}
private @trusted
{
enum Kind
{
METACODE,
CODESTR,
STR_IN_METACODE,
ALT_IN_METACODE,
RAW_IN_METACODE,
QUO_IN_METACODE,
}
struct Slice
{
static bool startsWith(string s, string u)
{
return (s.length >= u.length && s[0..u.length] == u);
}
static string match(Pred)(string s, Pred pred)
{
static if (isCallable!Pred)
{
size_t eaten = 0;
while (eaten < s.length && pred(s[eaten]))
++eaten;
if (eaten)
return s[0..eaten];
return null;
}
else static if (isSomeString!Pred)
{
// pragma(msg, "std.metastrings.match!Pred : typeof(s)=", typeof(s), ", typeof(pred)=", typeof(pred));
if (startsWith(s, pred))
return s[0 .. pred.length];
return null;
}
}
Kind current;
string buffer;
size_t eaten;
this(Kind c, string h, string t=null)
{
current = c;
if (t is null)
{
buffer = h;
eaten = 0;
}
else
{
buffer = h ~ t;
eaten = h.length;
}
}
bool chomp(string s)
{
auto res = startsWith(tail, s);
if (res)
eaten += s.length;
return res;
}
void chomp(size_t n)
{
if (eaten + n <= buffer.length)
eaten += n;
}
@property bool exist() {return eaten < buffer.length;}
@property string head() {return buffer[0..eaten];}
@property string tail() {return buffer[eaten..$];}
bool parseEsc()
{
if (chomp(`\`))
{
if (chomp("x"))
chomp(2);
else
chomp(1);
return true;
}
else
return false;
}
bool parseStr()
{
if (chomp(`"`))
{
auto save_head = head; // workaround for ctfe
auto s = Slice(
(current == Kind.METACODE ? Kind.STR_IN_METACODE : current),
tail);
while (s.exist && !s.chomp(`"`))
{
if (s.parseVar()) continue;
if (s.parseEsc()) continue;
s.chomp(1);
}
this = Slice(
current,
(current == Kind.METACODE
? save_head[0..$-1] ~ `(text("` ~ s.head[0..$-1] ~ `"))`
: save_head[0..$] ~ s.head[0..$]),
s.tail);
return true;
}
else
return false;
}
bool parseAlt()
{
if (chomp("`"))
{
auto save_head = head; // workaround for ctfe
auto s = Slice(
(current == Kind.METACODE ? Kind.ALT_IN_METACODE : current),
tail);
while (s.exist && !s.chomp("`"))
{
if (s.parseVar()) continue;
s.chomp(1);
}
this = Slice(
current,
(current == Kind.METACODE
? save_head[0..$-1] ~ "(text(`" ~ s.head[0..$-1] ~ "`))"
: save_head[0..$-1] ~ "` ~ \"`\" ~ `" ~ s.head[0..$-1] ~ "` ~ \"`\" ~ `"),
s.tail);
return true;
}
else
return false;
}
bool parseRaw()
{
if (chomp(`r"`))
{
auto save_head = head; // workaround for ctfe
auto s = Slice(
(current == Kind.METACODE ? Kind.RAW_IN_METACODE : current),
tail);
while (s.exist && !s.chomp(`"`))
{
if (s.parseVar()) continue;
s.chomp(1);
}
this = Slice(
current,
(current == Kind.METACODE
? save_head[0..$-2] ~ `(text(r"` ~ s.head[0..$-1] ~ `"))`
: save_head[0..$] ~ s.head[0..$]),
s.tail);
return true;
}
else
return false;
}
bool parseQuo()
{
if (chomp(`q{`))
{
auto save_head = head; // workaround for ctfe
auto s = Slice(
(current == Kind.METACODE ? Kind.QUO_IN_METACODE : current),
tail);
if (s.parseCode!`}`())
{
this = Slice(
current,
(current == Kind.METACODE
? save_head[0..$-2] ~ `(text(q{` ~ s.head[0..$-1] ~ `}))`
: save_head[] ~ s.head),
s.tail);
}
return true;
}
else
return false;
}
bool parseBlk()
{
if (chomp(`{`))
return parseCode!`}`();
else
return false;
}
bool parseComment()
{
if (chomp(`//`))
{
while (exist && !chomp("\n"))
chomp(1);
return true;
}
else if (chomp(`/*`))
{
while (exist && !chomp(`*/`))
chomp(1);
return true;
}
return false;
}
bool parseNestedComment()
{
if (chomp(`/+`))
{
while (exist && !chomp(`+/`))
{
if (parseNestedComment()) continue;
chomp(1);
}
return true;
}
return false;
}
private void checkVarNested()
{
if (current == Kind.METACODE)
if (__ctfe)
assert(0, "Invalid var in raw-code.");
else
throw new Exception("Invalid var in raw-code.");
}
private string encloseVar(string exp)
{
string open, close;
final switch(current)
{
case Kind.METACODE: assert(0);
case Kind.CODESTR: open = "`" , close = "`"; break;
case Kind.STR_IN_METACODE: open = `"` , close = `"`; break;
case Kind.ALT_IN_METACODE: open = "`" , close = "`"; break;
case Kind.RAW_IN_METACODE: open = `r"`, close = `"`; break;
case Kind.QUO_IN_METACODE: open = `q{`, close = `}`; break;
}
// return close ~ " ~ .std.conv.to!string(toStringNow!("~exp~")) ~ " ~ open;
return close ~ ", toStringNow!("~exp~"), " ~ open;
}
bool parseVar()
{
if (auto r = match(tail, `$`))
{
auto t = tail[1..$];
static bool isIdtHead(dchar c) { return c=='_' || isalpha(c); }
static bool isIdtTail(dchar c) { return c=='_' || isalnum(c); }
if (match(t, `{`))
{
checkVarNested();
auto s = Slice(Kind.METACODE, t[1..$]);
s.parseCode!`}`();
this = Slice(current, head ~ encloseVar(s.head[0..$-1]), s.tail);
return true;
}
else if (auto r = match(t[0..1], &isIdtHead))
{
checkVarNested();
auto id = t[0 .. 1 + match(t[1..$], &isIdtTail).length];
this = Slice(current, head ~ encloseVar(id), t[id.length .. $]);
return true;
}
return false;
}
return false;
}
bool parseCode(string end=null)()
{
enum endCheck = end ? "!chomp(end)" : "true";
while (exist && mixin(endCheck))
{
if (parseStr()) continue;
if (parseAlt()) continue;
if (parseRaw()) continue;
if (parseQuo()) continue;
if (parseBlk()) continue;
if (parseVar()) continue;
if (parseComment()) continue;
if (parseNestedComment()) continue;
chomp(1);
}
return true;
}
}
}
/**
Expand expression in string literal, with mixin expression.
Expression in ${ ... } is implicitly converted to string (requires importing std.conv.to)
If expreesion is single variable, you can omit side braces.
--------------------
enum int a = 10;
enum string op = "+";
static assert(mixin(expand!q{ ${a*2} $op 2 }) == q{ 20 + 2 });
// a*2 is caluclated in this scope, and converted to string.
--------------------
Other example, it is easy making parameterized code-blocks.
--------------------
template DefFunc(string name)
{
// generates specified name function.
mixin(
mixin(expand!q{
int ${name}(int a){ return a; }
})
);
}
--------------------
*/
template expand(string s)
{
enum expand = "text(" ~ expandSplit!s ~ ")";
}
template expandSplit(string s)
{
enum expandSplit = "TypeTuple!(" ~ splitVars(s) ~ ")";
}
string splitVars(string code)
{
auto s = Slice(Kind.CODESTR, code);
s.parseCode();
return "`" ~ s.buffer ~ "`";
}
version(unittest)
{
enum op = "+";
template ExpandTemp(string A)
{
enum ExpandTemp = "expanded_Temp";
}
template ExpandTest(int n)
{
}
template ExpandType(alias A)
{
alias typeof(A) ExpandType;
}
}
unittest
{
// var in code
static assert(mixin(expand!q{a ${op} b}) == q{a + b});
// alt-string in code
static assert(mixin(expand!q{`raw string`}) == q{`raw string`});
// var in string
static assert(mixin(expand!q{"a ${op} b"}) == q{"a + b"});
// var in raw-string
static assert(mixin(expand!q{r"a ${op} b"}) == q{r"a + b"});
// var in alt-string
static assert(mixin(expand!q{`a ${op} b`}) == q{`a + b`});
// var in quoted-string
static assert(mixin(expand!q{q{a ${op} b}}) == q{q{a + b}});
static assert(mixin(expand!q{ExpandTemp!q{ x ${op} y }}) == q{ExpandTemp!q{ x + y }});
// escape sequence test
static assert(mixin(expand!q{"\a"}) == q{"\a"});
static assert(mixin(expand!q{"\xA1"}) == q{"\xA1"});
static assert(mixin(expand!q{"\""}) == q{"\""});
// var in var
static assert(!__traits(compiles, mixin(expand!q{${ a ${op} b }}) ));
static assert(mixin(expand!q{"\0"}) == q{"\0"});
static assert(mixin(expand!q{"\01"}) == q{"\01"});
static assert(mixin(expand!q{"\012"}) == q{"\012"});
static assert(mixin(expand!q{"\u0FFF"}) == q{"\u0FFF"});
static assert(mixin(expand!q{"\U00000FFF"}) == q{"\U00000FFF"});
// var in string in var
static assert(mixin(expand!q{${ ExpandTemp!" x ${op} y " }}) == "expanded_Temp");
// var in raw-string in var
static assert(mixin(expand!q{${ ExpandTemp!r" x ${op} y " }}) == "expanded_Temp");
// var in alt-string in var
static assert(mixin(expand!q{${ ExpandTemp!` x ${op} y ` }}) == "expanded_Temp");
// var in quoted-string in var
static assert(mixin(expand!q{${ ExpandTemp!q{ x ${op} y } }}) == "expanded_Temp");
// non-paren identifier var
enum string var = "test";
static assert(mixin(expand!"ex: $var") == "ex: test");
enum string var1234 = "test";
static assert(mixin(expand!"ex: $var1234") == "ex: test");
enum string _var = "test";
static assert(mixin(expand!"ex: $_var!") == "ex: test!");
// type stringnize
alias double Double;
struct S{}
class C{}
static assert(mixin(expand!q{enum t = "$int";}) == q{enum t = "int";});
static assert(mixin(expand!q{enum t = "$Double";}) == q{enum t = "double";});
static assert(mixin(expand!q{enum t = "new $S()";}) == q{enum t = "new S()";});
static assert(mixin(expand!q{enum t = "new $C()";}) == q{enum t = "new C()";});
static assert(mixin(expand!q{enum t = "${ExpandType!`str`}";}) == q{enum t = "string";});
static assert(mixin(expand!q{enum t = "${ExpandTest!(10)}";}) == q{enum t = "ExpandTest!(10)";}); // template name
}
// sample unittest
unittest
{
enum int a = 10;
enum string op = "+";
static assert(mixin(expand!q{ ${a*2} $op 2 }) == q{ 20 + 2 });
assert(text(mixin(expandSplit!"I call you $a times.")) == "I call you 10 times.");
}