-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPatternParser.cs
More file actions
370 lines (347 loc) · 16.8 KB
/
PatternParser.cs
File metadata and controls
370 lines (347 loc) · 16.8 KB
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
using ReadableRex.Patterns;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace ReadableRex.Parsing
{
/// <summary>
/// Represents the result of parsing a pattern, including the parsed pattern, success status, and any error message.
/// </summary>
/// <remarks>This class provides information about the outcome of a pattern parsing operation. It includes
/// the parsed pattern, a boolean indicating whether the parsing was successful, and an error message if the parsing
/// failed.</remarks>
public class PatternParseResult
{
/// <summary>
/// The parsed <see cref="Pattern"/> object resulting from the parsing operation.
/// </summary>
public Pattern Pattern { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the operation was successful.
/// </summary>
public bool Success { get; set; }
/// <summary>
/// Gets or sets the error message associated with the current operation.
/// </summary>
public string ErrorMessage { get; set; }
}
/// <summary>
/// Provides functionality to parse expressions into <see cref="Pattern"/> objects.
/// </summary>
/// <remarks>The <see cref="PatternParser"/> class is designed to interpret a string expression and
/// convert it into a <see cref="Pattern"/> object by evaluating the expression's tokens. It supports parsing of
/// method calls and property accesses on the <see cref="Pattern"/> type.</remarks>
public static class PatternParser
{
/// <summary>
/// Attempts to parse the specified expression into a <see cref="Pattern"/> object.
/// </summary>
/// <remarks>The expression is tokenized and interpreted as a series of property and method
/// accesses on a <see cref="Pattern"/> object. The parsing process will skip an initial "With" token if
/// present.</remarks>
/// <param name="expression">The expression to parse, which should represent a sequence of property and method calls on a <see
/// cref="Pattern"/> object.</param>
/// <returns>A <see cref="PatternParseResult"/> indicating whether the parsing was successful. If successful, the <see
/// cref="PatternParseResult.Pattern"/> property will contain the resulting <see cref="Pattern"/> object;
/// otherwise, the <see cref="PatternParseResult.ErrorMessage"/> will contain an error message.</returns>
public static PatternParseResult TryParse(string expression)
{
try
{
var tokens = Tokenize(expression);
object current = typeof(Pattern).GetProperty("With").GetValue(null);
int startIndex = 0;
// If the first token is "With", skip it
if (tokens.Count > 0 && tokens[0].name == "With")
startIndex = 1;
for (int i = startIndex; i < tokens.Count; i++)
{
string name = tokens[i].name;
string param = tokens[i].param;
Type type = current.GetType();
// Check for property
var prop = type.GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
if (prop != null)
{
current = prop.GetValue(current);
continue;
}
// Check for method
var method = type.GetMethod(name, BindingFlags.Public | BindingFlags.Instance);
if (method != null)
{
object[] args = ParseParameters(param, method);
current = method.Invoke(current, args);
continue;
}
// Unknown member
return new PatternParseResult
{
Success = false,
ErrorMessage = $"Unknown member: {name}"
};
}
return new PatternParseResult
{
Success = true,
Pattern = (Pattern)current
};
}
catch (Exception ex)
{
return new PatternParseResult
{
Success = false,
ErrorMessage = $"Error parsing expression: {ex.Message}"
};
}
}
/// <summary>
/// Unescapes a string by replacing escape sequences with their corresponding characters.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
private static string UnescapeString(string input)
{
// Handles common C# escape sequences
var sb = new StringBuilder();
for (int i = 0; i < input.Length; i++)
{
if (input[i] == '\\' && i + 1 < input.Length)
{
i++;
switch (input[i])
{
case '\\': sb.Append('\\'); break;
case '\'': sb.Append('\''); break;
case '\"': sb.Append('\"'); break;
case 'n': sb.Append('\n'); break;
case 'r': sb.Append('\r'); break;
case 't': sb.Append('\t'); break;
case 'b': sb.Append('\b'); break;
case 'f': sb.Append('\f'); break;
case '0': sb.Append('\0'); break;
default: sb.Append(input[i]); break; // Unknown escape, keep as-is
}
}
else
{
sb.Append(input[i]);
}
}
return sb.ToString();
}
/// <summary>
/// Parses a string representation of method parameters into an array of objects suitable for invoking a method
/// with the specified <see cref="MethodInfo"/>.
/// </summary>
/// <remarks>This method supports parsing of parameters with complex types, including those
/// enclosed in quotes or parentheses. If the method has a parameter marked with <see
/// cref="ParamArrayAttribute"/>, the remaining parameters are collected into an array for that
/// parameter.</remarks>
/// <param name="param">The string containing the parameter values, separated by commas. The string should not include the
/// enclosing parentheses.</param>
/// <param name="method">The <see cref="MethodInfo"/> representing the method for which the parameters are being parsed. This is
/// used to determine the expected parameter types.</param>
/// <returns>An array of objects representing the parsed parameters, ready to be passed to the method specified by
/// <paramref name="method"/>.</returns>
/// <exception cref="ArgumentException">Thrown if the number of parameters in <paramref name="param"/> does not match the number of parameters
/// expected by <paramref name="method"/>, or if the parameters cannot be converted to the expected types.</exception>
public static object[] ParseParameters(string param, MethodInfo method)
{
if (string.IsNullOrWhiteSpace(param)) return new object[0];
param = param.Trim('(', ')');
var parameters = method.GetParameters();
// If only one parameter, treat the whole param string as one argument
if (parameters.Length == 1)
{
return new[] { ConvertArg(param.Trim(), parameters[0].ParameterType) };
}
// Otherwise, split by top-level commas (not inside quotes/parentheses)
var paramParts = new List<string>();
int depth = 0;
bool inSingleQuote = false, inDoubleQuote = false;
var sb = new StringBuilder();
for (int i = 0; i < param.Length; i++)
{
char c = param[i];
if (c == '\'' && !inDoubleQuote) inSingleQuote = !inSingleQuote;
else if (c == '"' && !inSingleQuote) inDoubleQuote = !inSingleQuote;
else if (!inSingleQuote && !inDoubleQuote)
{
if (c == '(') depth++;
else if (c == ')') depth--;
else if (c == ',' && depth == 0)
{
paramParts.Add(sb.ToString().Trim());
sb.Clear();
continue;
}
}
sb.Append(c);
}
if (sb.Length > 0) paramParts.Add(sb.ToString().Trim());
// Check if last parameter is params
bool hasParams = parameters.Length > 0 && Attribute.IsDefined(parameters.Last(), typeof(ParamArrayAttribute));
if (hasParams)
{
int fixedCount = parameters.Length - 1;
if (paramParts.Count < fixedCount)
throw new ArgumentException("Parameter count mismatch.");
var args = new List<object>();
// Add fixed parameters
for (int i = 0; i < fixedCount; i++)
args.Add(ConvertArg(paramParts[i], parameters[i].ParameterType));
// Collect remaining as array for params
var paramsType = parameters.Last().ParameterType.GetElementType();
var paramsArgs = paramParts.Skip(fixedCount)
.Select(p => ConvertArg(p, paramsType))
.ToArray();
Array arr = Array.CreateInstance(paramsType, paramsArgs.Length);
for (int i = 0; i < paramsArgs.Length; i++)
arr.SetValue(paramsArgs[i], i);
args.Add(arr);
return args.ToArray();
}
else
{
if (paramParts.Count != parameters.Length)
throw new ArgumentException("Parameter count mismatch.");
var args = new List<object>();
for (int i = 0; i < parameters.Length; i++)
args.Add(ConvertArg(paramParts[i], parameters[i].ParameterType));
return args.ToArray();
}
}
/// <summary>
/// Converts a string representation of a value to a specified type.
/// </summary>
/// <remarks>This method supports conversion to several primitive types, enums, arrays, and custom
/// types like <c>Pattern</c>. For string conversions, it handles quoted strings and unescapes them
/// appropriately.</remarks>
/// <param name="arg">The string representation of the value to convert.</param>
/// <param name="paramType">The type to which the value should be converted.</param>
/// <returns>An object of the specified type <paramref name="paramType"/> that represents the converted value.</returns>
/// <exception cref="ArgumentException">Thrown if the conversion fails or if <paramref name="paramType"/> is not supported.</exception>
private static object ConvertArg(string arg, Type paramType)
{
if (paramType == typeof(int) && int.TryParse(arg, out int intVal))
return intVal;
if (paramType == typeof(double) && double.TryParse(arg, out double doubleVal))
return doubleVal;
if (paramType == typeof(bool) && bool.TryParse(arg, out bool boolVal))
return boolVal;
if (paramType == typeof(char) && arg.Length == 1)
return arg[0];
if (paramType.IsEnum)
return Enum.Parse(paramType, arg, true);
if (paramType == typeof(string))
{
if ((arg.StartsWith("'") && arg.EndsWith("'")) ||
(arg.StartsWith("\"") && arg.EndsWith("\"")))
{
string unquoted = arg.Substring(1, arg.Length - 2);
return UnescapeString(unquoted);
}
return UnescapeString(arg);
}
// Handle params string[] and other array types
if (paramType.IsArray)
{
var elementType = paramType.GetElementType();
// Split by comma, but not inside quotes/parentheses
var items = new List<string>();
int depth = 0;
bool inSingleQuote = false, inDoubleQuote = false;
var sb = new StringBuilder();
for (int i = 0; i < arg.Length; i++)
{
char c = arg[i];
if (c == '\'' && !inDoubleQuote) inSingleQuote = !inSingleQuote;
else if (c == '"' && !inSingleQuote) inDoubleQuote = !inDoubleQuote;
else if (!inSingleQuote && !inDoubleQuote)
{
if (c == '(') depth++;
else if (c == ')') depth--;
else if (c == ',' && depth == 0)
{
items.Add(sb.ToString().Trim());
sb.Clear();
continue;
}
}
sb.Append(c);
}
if (sb.Length > 0) items.Add(sb.ToString().Trim());
Array arr = Array.CreateInstance(elementType, items.Count);
for (int i = 0; i < items.Count; i++)
arr.SetValue(ConvertArg(items[i], elementType), i);
return arr;
}
if (paramType == typeof(Pattern))
{
string nestedExpr = arg;
if (nestedExpr.StartsWith("(") && nestedExpr.EndsWith(")"))
nestedExpr = nestedExpr.Substring(1, nestedExpr.Length - 2).Trim();
var result = TryParse(nestedExpr.TrimStart('.'));
if (!result.Success)
throw new ArgumentException($"Nested pattern parse error: {result.ErrorMessage}");
return result.Pattern;
}
throw new ArgumentException($"Unsupported parameter type: {paramType.Name}");
}
/// <summary>
/// Tokenizes the specified expression into a list of name-parameter pairs.
/// </summary>
/// <remarks>The method processes the input expression by identifying names and their optional
/// parameters, ignoring whitespace and dots. Names are sequences of letters, digits, or underscores, and
/// parameters are enclosed in parentheses.</remarks>
/// <param name="expression">The expression to tokenize, consisting of names and optional parameters.</param>
/// <returns>A list of tuples, where each tuple contains a name and its associated parameter from the expression. The
/// parameter is null if no parameter is associated with the name.</returns>
private static List<(string name, string param)> Tokenize(string expression)
{
var tokens = new List<(string name, string param)>();
int i = 0;
while (i < expression.Length)
{
// Skip whitespace and dots
while (i < expression.Length && (char.IsWhiteSpace(expression[i]) || expression[i] == '.'))
i++;
if (i >= expression.Length) break;
// Parse name
int start = i;
while (i < expression.Length && (char.IsLetterOrDigit(expression[i]) || expression[i] == '_'))
i++;
if (start == i) break; // No valid name
string name = expression.Substring(start, i - start);
// Parse parameter (if any)
string param = null;
if (i < expression.Length && expression[i] == '(')
{
int depth = 0;
int paramStart = i;
while (i < expression.Length)
{
if (expression[i] == '(') depth++;
else if (expression[i] == ')')
{
depth--;
if (depth == 0)
{
i++; // include closing parenthesis
break;
}
}
i++;
}
param = expression.Substring(paramStart, i - paramStart);
}
tokens.Add((name, param));
}
return tokens;
}
}
}