1 module dadt.util;
2 import std.string;
3 
4 string patternReplaceWithTable(string code, string[string] table) {
5   string[] codes;
6   size_t[][string] targets;
7   bool in_bracket;
8   string buf;
9 
10   for (size_t i = 0; i < code.length; i++) {
11     char ch = code[i];
12 
13     if (!in_bracket) {
14       if (ch == '#') {
15         if (i + 1 < code.length && code[i + 1] == '{') {
16           in_bracket = true;
17           i++;
18 
19           codes ~= buf;
20           buf = "";
21           continue;
22         } else {
23           throw new Error("Syntax Error");
24         }
25       } else {
26         buf ~= ch;
27       }
28     } else {
29       if (ch == '}') {
30         if (i + 1 < code.length && code[i + 1] == '#') {
31           in_bracket = false;
32           i++;
33 
34           codes ~= buf;
35           targets[buf] ~= codes.length - 1;
36           buf = "";
37           continue;
38         } else {
39           buf ~= ch;
40         }
41       } else {
42         buf ~= ch;
43       }
44     }
45   }
46 
47   if (buf.length) {
48     codes ~= buf;
49   }
50 
51   foreach (key, value; table) {
52     size_t[] idxes = targets[key];
53     foreach (idx; idxes) {
54       codes[idx] = value;
55     }
56   }
57 
58   return codes.join;
59 }