forked from sourcegit-scm/sourcegit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuery.cs
More file actions
568 lines (499 loc) · 20.5 KB
/
Copy pathQuery.cs
File metadata and controls
568 lines (499 loc) · 20.5 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
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
using System;
using System.Collections.Generic;
using System.Linq;
namespace SourceGit.Controls
{
#region SPEC
public enum ExprOp
{
Term,
And,
Or,
Not
}
public class ExprNode
{
public ExprOp Op { get; set; }
public List<ExprNode> Children { get; set; }
public string Prefix { get; set; }
public string Value { get; set; }
public object TypedValue { get; set; }
public override string ToString()
{
if (Op == ExprOp.Term)
return string.IsNullOrEmpty(Prefix) ? Value : $"{Prefix}:{Value}";
if (Op == ExprOp.Not)
return $"-( {Children?[0]} )";
var joiner = Op == ExprOp.And ? " AND " : " OR ";
return $"( {string.Join(joiner, Children ?? [])} )";
}
}
public class GroupSpec
{
public string ProviderPrefix { get; set; }
public ExprNode Expr { get; set; }
}
public class QuerySpec
{
public List<GroupSpec> Groups { get; set; } = new List<GroupSpec>();
public List<string> FallbackTerms { get; set; } = new List<string>();
public List<string> FallbackNotTerms { get; set; } = new List<string>();
public List<QuerySpec> SubGroups { get; set; } = new List<QuerySpec>();
public bool HasSubGroups => SubGroups.Count > 0;
}
#endregion
#region EVALUATOR
public static class ExprEvaluator
{
public static bool Evaluate(ExprNode node, Func<ExprNode, bool> termEvaluator)
{
if (node == null)
return true;
switch (node.Op)
{
case ExprOp.Term:
return termEvaluator(node);
case ExprOp.Not:
return !Evaluate(node.Children?[0], termEvaluator);
case ExprOp.And:
if (node.Children == null || node.Children.Count == 0)
return true;
foreach (var child in node.Children)
if (!Evaluate(child, termEvaluator))
return false;
return true;
case ExprOp.Or:
if (node.Children == null || node.Children.Count == 0)
return true;
foreach (var child in node.Children)
if (Evaluate(child, termEvaluator))
return true;
return false;
default:
return true;
}
}
}
#endregion
#region PARSER
public static class QueryParser
{
public static ExprNode ParseInlineExpr(string value)
{
if (string.IsNullOrWhiteSpace(value))
return null;
var segments = new List<string>();
var operators = new List<ExprOp>();
var start = 0;
for (int i = 0; i < value.Length - 1; i++)
{
if (value[i] == '|' && value[i + 1] == '|')
{
var part = value[start..i].Trim();
if (!string.IsNullOrEmpty(part))
segments.Add(part);
operators.Add(ExprOp.Or);
start = i + 2;
i++;
continue;
}
if (value[i] == '&' && value[i + 1] == '&')
{
var part = value[start..i].Trim();
if (!string.IsNullOrEmpty(part))
segments.Add(part);
operators.Add(ExprOp.And);
start = i + 2;
i++;
}
}
var tail = value[start..].Trim();
if (!string.IsNullOrEmpty(tail))
segments.Add(tail);
if (segments.Count == 0)
return null;
var terms = segments.Select(s => ExpandImplicitPrefix(s, segments[0]))
.ToList(); // Ensure all terms inherit the first segment's prefix
if (operators.Count == 0)
return terms[0];
// First pass: collapse all AND into grouped nodes.
var orBuckets = new List<ExprNode>();
var currentAndBucket = new List<ExprNode> { terms[0] };
for (int i = 0; i < operators.Count && i + 1 < terms.Count; i++)
{
var op = operators[i];
var nextTerm = terms[i + 1];
if (op == ExprOp.And)
{
currentAndBucket.Add(nextTerm);
}
else
{
orBuckets.Add(currentAndBucket.Count == 1
? currentAndBucket[0]
: new ExprNode { Op = ExprOp.And, Children = currentAndBucket.ToList() });
currentAndBucket = new List<ExprNode> { nextTerm };
}
}
orBuckets.Add(currentAndBucket.Count == 1
? currentAndBucket[0]
: new ExprNode { Op = ExprOp.And, Children = currentAndBucket.ToList() });
return orBuckets.Count == 1 ? orBuckets[0] : new ExprNode { Op = ExprOp.Or, Children = orBuckets };
}
private static ExprNode ExpandImplicitPrefix(string term, string reference)
{
if (string.IsNullOrWhiteSpace(term))
return null;
var colonIndex = reference.IndexOf(':');
if (colonIndex > 0 && colonIndex < reference.Length - 1)
{
var prefix = reference.Substring(0, colonIndex);
return new ExprNode { Op = ExprOp.Term, Prefix = prefix, Value = term };
}
return new ExprNode { Op = ExprOp.Term, Value = term };
}
private static ExprNode MergeNodesByMode(List<ExprNode> nodes, TokenLogicMode mode)
{
if (nodes == null || nodes.Count == 0)
return null;
if (mode == TokenLogicMode.SingleReplace)
return nodes.Last();
if (nodes.Count == 1)
return nodes[0];
var op = mode == TokenLogicMode.AutoAnd ? ExprOp.And : ExprOp.Or;
return new ExprNode { Op = op, Children = nodes };
}
public static List<List<TokenInstance>> PartitionByParentheses(IEnumerable<TokenInstance> tokens)
{
var result = new List<List<TokenInstance>>();
var current = new List<TokenInstance>();
int depth = 0;
bool hasParens = false;
foreach (var token in tokens)
{
if (token == null)
continue;
if (token.Raw == "(")
{
hasParens = true;
if (depth == 0 && current.Count > 0)
{
result.Add(current);
current = new List<TokenInstance>();
}
depth++;
}
else if (token.Raw == ")")
{
if (depth > 0)
{
depth--;
if (depth == 0 && current.Count > 0)
{
result.Add(current);
current = new List<TokenInstance>();
}
}
}
else
{
current.Add(token);
}
}
if (current.Count > 0 || (!hasParens && result.Count == 0))
result.Add(current);
return result;
}
public static QuerySpec Parse(IEnumerable<string> tokens, IEnumerable<ITokenSuggestionProvider> providers)
{
var instances = tokens?.Select(t => new TokenInstance
{
Raw = t,
IsOperator = t is "||" or "&&" or "|" or
"&" or "(" or ")"
}) ??
Enumerable.Empty<TokenInstance>();
return Parse(instances, providers);
}
public static QuerySpec Parse(IEnumerable<TokenInstance> tokens, IEnumerable<ITokenSuggestionProvider> providers)
{
var tokenList = tokens.ToList();
var providersList = providers.ToList();
// Check for parenthesized grouping
var subGroups = PartitionByParentheses(tokenList);
if (subGroups.Count > 1)
{
// Multiple sub-groups: each is AND-ed internally, OR-ed across groups
var spec = new QuerySpec();
foreach (var groupTokens in subGroups)
{
if (groupTokens.Count == 0)
continue;
if (groupTokens.Count == 1 && groupTokens[0].IsOperator)
continue;
spec.SubGroups.Add(ParseGroup(groupTokens, providersList));
}
return spec;
}
// Check for cross-prefix || operators that should create OR sub-groups
var orSubGroups = PartitionByCrossProviderOr(tokenList, providersList);
if (orSubGroups.Count > 1)
{
var spec = new QuerySpec();
foreach (var groupTokens in orSubGroups)
{
if (groupTokens.Count == 0)
continue;
spec.SubGroups.Add(ParseGroup(groupTokens, providersList));
}
return spec;
}
// Single group (no parens, no cross-prefix ||)
return ParseGroup(tokenList, providersList);
}
private static List<List<TokenInstance>> PartitionByCrossProviderOr(List<TokenInstance> tokens,
List<ITokenSuggestionProvider> providers)
{
// Build a quick provider lookup for each token
var tokenProviders = new ITokenSuggestionProvider[tokens.Count];
for (int i = 0; i < tokens.Count; i++)
{
var t = tokens[i];
if (t.IsOperator)
continue;
if (t.Provider != null)
{
tokenProviders[i] = t.Provider;
continue;
}
var check = t.Raw.StartsWith("-") ? t.Raw[1..] : t.Raw;
foreach (var p in providers)
{
if (check.StartsWith(p.Prefix, StringComparison.OrdinalIgnoreCase) ||
(p.FullPrefix != null &&
p.FullPrefix.Any(fp => check.StartsWith(fp, StringComparison.OrdinalIgnoreCase))))
{
tokenProviders[i] = p;
break;
}
}
}
// Find split points: || between different providers
var splitAfter = new HashSet<int>();
for (int i = 0; i < tokens.Count; i++)
{
if (tokens[i].Raw is "||" or "|")
{
// Find previous non-operator token's provider
ITokenSuggestionProvider prevProvider = null;
for (int j = i - 1; j >= 0; j--)
{
if (tokenProviders[j] != null)
{
prevProvider = tokenProviders[j];
break;
}
}
// Find next non-operator token's provider
ITokenSuggestionProvider nextProvider = null;
for (int j = i + 1; j < tokens.Count; j++)
{
if (tokenProviders[j] != null)
{
nextProvider = tokenProviders[j];
break;
}
}
if (prevProvider != nextProvider)
splitAfter.Add(i);
}
}
if (splitAfter.Count == 0)
return [tokens];
// Split tokens at the identified points
var result = new List<List<TokenInstance>>();
var current = new List<TokenInstance>();
for (int i = 0; i < tokens.Count; i++)
{
current.Add(tokens[i]);
if (splitAfter.Contains(i))
{
result.Add(current);
current = new List<TokenInstance>();
}
}
if (current.Count > 0)
result.Add(current);
return result;
}
private static QuerySpec ParseGroup(List<TokenInstance> tokens, List<ITokenSuggestionProvider> providersList)
{
var spec = new QuerySpec();
var groups = new Dictionary<ITokenSuggestionProvider, (List<ExprNode> pos, List<ExprNode> neg)>();
var explicitPosOps = new Dictionary<ITokenSuggestionProvider, List<ExprOp>>();
ITokenSuggestionProvider lastPosProvider = null;
ExprOp? pendingOp = null;
foreach (var t in tokens)
{
var token = t.Raw;
if (string.IsNullOrWhiteSpace(token))
continue;
if (token is "||" or "&&" or "|" or "&")
{
pendingOp = token switch
{
"||" or "|" => ExprOp.Or,
"&&" or "&" => ExprOp.And,
_ => ExprOp.Or,
};
continue;
}
bool isNegative = token.StartsWith("-", StringComparison.Ordinal);
string testToken = isNegative ? token[1..] : token;
ITokenSuggestionProvider matchedProvider = t.Provider;
string matchedPrefix = t.Provider?.Prefix;
if (matchedProvider == null)
{
foreach (var p in providersList)
{
if (testToken.StartsWith(p.Prefix, StringComparison.OrdinalIgnoreCase))
{
matchedProvider = p;
matchedPrefix = p.Prefix;
break;
}
if (p.FullPrefix != null)
{
foreach (var fp in p.FullPrefix)
{
if (testToken.StartsWith(fp, StringComparison.OrdinalIgnoreCase))
{
matchedProvider = p;
matchedPrefix = fp;
break;
}
}
}
if (matchedProvider != null)
break;
}
}
if (matchedProvider != null)
{
var val = testToken.Substring(matchedPrefix.Length).Trim();
if (string.IsNullOrWhiteSpace(val))
continue;
var unescapedVal = TokenValueHelper.Unescape(val);
var inlineExpr = new ExprNode { Op = ExprOp.Term, Value = unescapedVal };
if (t.Value != null)
{
inlineExpr.TypedValue = t.Value;
}
else if (matchedProvider is IAdvancedTokenProvider advancedProvider &&
advancedProvider.ValueConverter != null)
{
inlineExpr.TypedValue = advancedProvider.ValueConverter.ToValue(unescapedVal);
}
// Track explicit operators between consecutive same-provider positive entries
if (!isNegative && lastPosProvider == matchedProvider && pendingOp.HasValue)
{
if (!explicitPosOps.ContainsKey(matchedProvider))
explicitPosOps[matchedProvider] = new List<ExprOp>();
explicitPosOps[matchedProvider].Add(pendingOp.Value);
}
if (!isNegative)
lastPosProvider = matchedProvider;
pendingOp = null;
if (!groups.ContainsKey(matchedProvider))
groups[matchedProvider] = (new List<ExprNode>(), new List<ExprNode>());
if (isNegative)
groups[matchedProvider].neg.Add(inlineExpr);
else
groups[matchedProvider].pos.Add(inlineExpr);
}
else
{
lastPosProvider = null;
pendingOp = null;
if (isNegative)
spec.FallbackNotTerms.Add(testToken.Trim());
else
spec.FallbackTerms.Add(testToken.Trim());
}
}
foreach (var kvp in groups)
{
var p = kvp.Key;
var posList = kvp.Value.pos;
var negList = kvp.Value.neg;
var groupSpec = new GroupSpec { ProviderPrefix = p.Prefix };
var groupNodes = new List<ExprNode>();
ExprNode positiveExpr = null;
if (posList.Count > 0)
{
// Check if explicit operators override the default LogicMode
if (explicitPosOps.TryGetValue(p, out var ops) && ops.Count == posList.Count - 1 && posList.Count >= 2)
{
var distinct = ops.Distinct().ToList();
if (distinct.Count == 1)
{
var defaultOp = p.LogicMode == TokenLogicMode.AutoAnd ? ExprOp.And : ExprOp.Or;
if (distinct[0] != defaultOp)
{
// Explicit operator overrides LogicMode default
positiveExpr = new ExprNode { Op = distinct[0], Children = new List<ExprNode>(posList) };
}
}
}
if (positiveExpr == null)
positiveExpr = MergeNodesByMode(posList, p.LogicMode);
if (positiveExpr != null)
groupNodes.Add(positiveExpr);
}
foreach (var negExpr in negList)
{
groupNodes.Add(new ExprNode { Op = ExprOp.Not, Children = [negExpr] });
}
if (groupNodes.Count > 0)
{
if (groupNodes.Count == 1)
{
groupSpec.Expr = groupNodes[0];
}
else
{
groupSpec.Expr = new ExprNode { Op = ExprOp.And, Children = groupNodes };
}
spec.Groups.Add(groupSpec);
}
}
return spec;
}
private static ITokenSuggestionProvider MatchProvider(IEnumerable<ITokenSuggestionProvider> providers, string text,
out string matchedPrefix)
{
foreach (var p in providers)
{
if (text.StartsWith(p.Prefix, StringComparison.OrdinalIgnoreCase))
{
matchedPrefix = p.Prefix;
return p;
}
if (p.FullPrefix != null)
{
foreach (var alias in p.FullPrefix)
{
if (text.StartsWith(alias, StringComparison.OrdinalIgnoreCase))
{
matchedPrefix = alias;
return p;
}
}
}
}
matchedPrefix = null;
return null;
}
}
#endregion
}