-
Notifications
You must be signed in to change notification settings - Fork 2
/
Conf.cs
350 lines (321 loc) · 13.3 KB
/
Conf.cs
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
namespace Conf
{
public class Node
{
public string Value { get; set; }
public List<Node> Children { get; set; }
}
/// <summary>
///
/// </summary>
/// <remarks>
/// Syntax:
/// Comment ::= '#' [^\r\n]*
/// WS ::= (' ' | '\t' | '\r' | '\n')+
/// String ::= [^\r\n\t #'"{}=]+ | ("'" [^']* "'") | ('"' [^"]* '"')
/// Node ::= String [WS? '{' Children '}' | WS? '=' WS? Node]
/// Children ::= WS? (Comment | Node) (WS (Comment | Node))* WS? | WS?
/// </remarks>
public class Parser
{
string input;
int curr;
int end;
Parser(string input, int start, int count)
{
this.input = input;
this.curr = start;
this.end = start + count;
}
public static List<Node> Parse(string text)
{
return new Parser(text, 0, text.Length).ReadChildren(false);
}
public static List<Node> Parse(string text, int start, int count)
{
return new Parser(text, start, count).ReadChildren(false);
}
public static List<Node> ParseCommandLine()
{
string commandLine = Environment.CommandLine;
Parser parser = new Parser(commandLine, 0, commandLine.Length);
string arg0;
parser.TryReadString(out arg0); // Skip the name of the executable
return parser.ReadChildren(false);
}
List<Node> ReadChildren(bool nested)
{
List<Node> children = new List<Node>();
TryReadWhiteSpace();
while (curr < end) {
// End of nested children
if (input[curr] == '}') {
if (nested) {
break;
} else {
throw new ParseException(curr, curr, "Superfluous '}'");
}
}
// Try to parse a comment
if (TryReadComment()) {
TryReadWhiteSpace();
} else {
// If it is not a comment, it must be a node
bool followedByWhiteSpace;
children.Add(ReadNode(out followedByWhiteSpace));
// The node has to be followed by whitespace or end of file or '}'
if (!followedByWhiteSpace && curr < end && input[curr] != '}') {
throw new ParseException(curr, curr, "Node has to be followed by whitespace");
}
}
}
return children;
}
Node ReadNode(out bool followedByWhiteSpace)
{
string value;
if (!TryReadString(out value))
throw new ParseException(curr, curr, "String value expected");
Node node = new Node();
node.Value = value;
followedByWhiteSpace = TryReadWhiteSpace();
if (curr < end && input[curr] == '=') {
curr++; // '='
TryReadWhiteSpace();
node.Children = new List<Node>(1);
node.Children.Add(ReadNode(out followedByWhiteSpace));
} else if (curr < end && input[curr] == '{') {
curr++; // '{'
node.Children = ReadChildren(true);
if (curr == end || input[curr] != '}')
throw new ParseException(curr, curr, "'}' Expected");
curr++; // '}'
followedByWhiteSpace = TryReadWhiteSpace();
}
return node;
}
bool TryReadWhiteSpace()
{
int start = curr;
while (curr < end && ((input[curr] <= ' ') && (input[curr] == ' ' || input[curr] == '\t' || input[curr] == '\r' || input[curr] == '\n'))) curr++;
return curr > start;
}
bool TryReadComment()
{
if (curr < end && input[curr] == '#') {
curr++; // '#'
while (curr < end && input[curr] != '\r' && input[curr] != '\n') curr++;
return true;
} else {
return false;
}
}
bool TryReadString(out string str)
{
if (curr == end) {
str = string.Empty;
return false;
}
int start = curr;
char first = input[curr];
if (first == '"' || first == '\'') {
// Quoted string
curr++;
int endQuote;
if (curr == end || (endQuote = input.IndexOf(first, curr)) == -1)
throw new ParseException(start, end, "Closing quote is missing");
curr = endQuote + 1;
str = ReslveReferences(start + 1, endQuote);
return true;
} else {
// Unquoted string
while (curr < end) {
char c = input[curr];
if (('A' <= c && c <= 'z') || ('0' <= c && c <= '9') || c > 0x80) {
curr++; // Quick pass test for the most common characters
} else {
if (c == ' ' || c == '=' || c == '\r' || c == '\n' || c == '\t' || c == '{' || c == '}' || c == '#' || c == '\'' || c == '"')
break; // String terminator
curr++; // Less common characters
}
}
str = ReslveReferences(start, curr);
return curr > start;
}
}
string ReslveReferences(int start, int end)
{
if (start == end)
return string.Empty;
if (input.IndexOf('&', start, end - start) == -1)
return input.Substring(start, end - start);
StringBuilder sb = new StringBuilder(end - start);
int pos = start;
while (pos < end) {
int amp = input.IndexOf('&', pos, end - pos);
if (amp == -1) {
sb.Append(input, pos, end - pos);
break;
} else {
sb.Append(input, pos, amp - pos);
int semicolon = input.IndexOf(';', amp, end - amp);
if (semicolon == -1)
throw new ParseException(amp, end, "';' is missing after '&'");
string refName = input.Substring(amp + 1, semicolon - amp - 1);
switch (refName) {
case "": throw new ParseException(amp, amp + 2, "Empty reference");
case "amp": sb.Append('&'); break;
case "apos": sb.Append('\''); break;
case "quot": sb.Append('\"'); break;
case "lt": sb.Append('<'); break;
case "gt": sb.Append('>'); break;
case "lb": sb.Append('{'); break;
case "rb": sb.Append('}'); break;
case "eq": sb.Append('='); break;
case "br": sb.Append('\n'); break;
case "cr": sb.Append('\r'); break;
case "tab": sb.Append('\t'); break;
case "nbsp": sb.Append((char)0xA0); break;
default:
// Unicode character
int utf32;
try {
if (refName.StartsWith("#x")) {
utf32 = int.Parse(refName.Substring(2), NumberStyles.AllowHexSpecifier);
} else if (refName[0] == '#') {
utf32 = int.Parse(refName.Substring(1), NumberStyles.None);
} else {
utf32 = int.Parse(refName, NumberStyles.AllowHexSpecifier);
}
}
catch {
throw new ParseException(amp + 1, semicolon, "Failed to parse reference '" + refName + "'");
} try {
sb.Append(char.ConvertFromUtf32(utf32));
} catch {
throw new ParseException(amp + 1, semicolon, "Invalid Unicode code point " + refName);
}
break;
}
pos = semicolon + 1;
}
}
return sb.ToString();
}
}
public class ParseException : Exception
{
public int Start { get; private set; }
public int End { get; private set; }
public ParseException(int start, int end, string message)
: base(message)
{
this.Start = start;
this.End = end;
}
}
public class PrettyPrinter
{
StringBuilder sb;
int depth = 0;
public string Print(IEnumerable<Node> nodes)
{
sb = new StringBuilder();
Append(nodes);
return sb.ToString();
}
void Append(IEnumerable<Node> nodes)
{
foreach (Node node in nodes) {
// Delimiter
if (sb.Length > 0) {
sb.Append("\n");
sb.Append(' ', depth * 2);
}
// The value
Append(node.Value);
// Children
if (node.Children != null && node.Children.Count > 0) {
if (node.Children.Count == 1 && (node.Children[0].Children == null || node.Children[0].Children.Count == 0)) {
sb.Append(" =");
Append(node.Children[0].Value);
} else {
sb.Append(" {");
depth++;
Append(node.Children);
depth--;
sb.Append("\n");
sb.Append(' ', depth * 2);
sb.Append("}");
}
}
}
}
void Append(string val)
{
if (string.IsNullOrEmpty(val)) {
sb.Append("\"\"");
} else if (val.IndexOfAny(new char[] { '\r', '\n', '\t', ' ', '#', '\'', '"', '{', '}', '=' }) == -1) {
sb.Append(val);
} else {
if (val.Contains("\"") && !val.Contains("\'")) {
sb.Append('\'');
sb.Append(val);
sb.Append('\'');
} else {
sb.Append('\"');
sb.Append(val.Replace("\"", """));
sb.Append('\"');
}
}
}
}
public static class Deserializer
{
public static void LoadAppConfig<T>()
{
// Set properties from the .conf file
string assembyPath = Assembly.GetEntryAssembly().Location;
string confPath = Path.Combine(Path.GetDirectoryName(assembyPath), Path.GetFileNameWithoutExtension(assembyPath) + ".conf");
if (File.Exists(confPath)) {
string confText = File.ReadAllText(confPath);
Deserialize(Parser.Parse(confText), default(T));
}
// Set properties from command line
Deserialize(Parser.ParseCommandLine(), default(T));
}
public static void Deserialize<T>(List<Node> from, T to)
{
foreach (Node node in from) {
string name = node.Value.TrimStart('-');
FieldInfo field = typeof(T).GetField(name, BindingFlags.Public | BindingFlags.Static);
if (field != null) {
if (field.FieldType == typeof(TimeSpan)) {
TimeSpan val;
TimeSpan.TryParse(node.Children[0].Value, out val);
field.SetValue(null, val);
} else if (field.FieldType == typeof(bool) && (node.Children == null || node.Children.Count == 0)) {
field.SetValue(null, true);
} else {
object val = Convert.ChangeType(node.Children[0].Value, field.FieldType);
field.SetValue(null, val);
}
} else {
StringBuilder sb = new StringBuilder();
foreach(FieldInfo fi in typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static)) {
sb.Append(fi.Name);
sb.Append(" ");
}
throw new Exception("Unknown option: " + name + Environment.NewLine + "Valid options: " + sb.ToString());
}
}
}
}
}