-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathAstSimplifier.cs
637 lines (551 loc) · 29.5 KB
/
AstSimplifier.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
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
/* Copyright 2010-present MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using MongoDB.Bson;
using MongoDB.Driver.Linq.Linq3Implementation.Ast.Expressions;
using MongoDB.Driver.Linq.Linq3Implementation.Ast.Filters;
using MongoDB.Driver.Linq.Linq3Implementation.Ast.Stages;
using MongoDB.Driver.Linq.Linq3Implementation.Ast.Visitors;
using MongoDB.Driver.Linq.Linq3Implementation.Misc;
namespace MongoDB.Driver.Linq.Linq3Implementation.Ast.Optimizers
{
internal class AstSimplifier : AstNodeVisitor
{
#region static
public static AstNode Simplify(AstNode node)
{
var simplifier = new AstSimplifier();
return simplifier.Visit(node);
}
public static TNode SimplifyAndConvert<TNode>(TNode node)
where TNode : AstNode
{
return (TNode)Simplify(node);
}
#endregion
public override AstNode VisitBinaryExpression(AstBinaryExpression node)
{
var arg1 = VisitAndConvert(node.Arg1);
var arg2 = VisitAndConvert(node.Arg2);
if (node.Operator == AstBinaryOperator.IfNull)
{
if (arg1 is AstConstantExpression arg1ConstantExpression)
{
// { $ifNull : [expr1, expr2] } => expr2 when expr1 == null
// { $ifNull : [expr1, expr2] } => expr1 when expr1 != null
return arg1ConstantExpression.Value == BsonNull.Value ? arg2 : arg1;
}
if (arg2 is AstConstantExpression arg2ConstantExpression &&
arg2ConstantExpression.Value == BsonNull.Value)
{
// { $ifNull : [expr1, expr2] } => expr1 when expr2 == null
return arg1;
}
}
return node.Update(arg1, arg2);
}
public override AstNode VisitCondExpression(AstCondExpression node)
{
// { $cond : [{ $eq : [expr1, null] }, null, expr2] }
if (node.If is AstBinaryExpression binaryIfpression &&
binaryIfpression.Operator == AstBinaryOperator.Eq &&
binaryIfpression.Arg1 is AstExpression expr1 &&
binaryIfpression.Arg2 is AstConstantExpression constantComparandExpression &&
constantComparandExpression.Value == BsonNull.Value &&
node.Then is AstConstantExpression constantThenExpression &&
constantThenExpression.Value == BsonNull.Value &&
node.Else is AstExpression expr2)
{
// { $cond : [{ $eq : [expr, null] }, null, expr] } => expr
if (expr1 == expr2)
{
return Visit(expr2);
}
// { $cond : [{ $eq : [expr, null] }, null, { $toT : expr }] } => { $toT : expr } for operators that map null to null
if (expr2 is AstUnaryExpression unaryElseExpression &&
OperatorMapsNullToNull(unaryElseExpression.Operator) &&
unaryElseExpression.Arg == expr1)
{
return Visit(expr2);
}
}
return base.VisitCondExpression(node);
static bool OperatorMapsNullToNull(AstUnaryOperator @operator)
{
return @operator switch
{
AstUnaryOperator.ToDecimal => true,
AstUnaryOperator.ToDouble => true,
AstUnaryOperator.ToInt => true,
AstUnaryOperator.ToLong => true,
_ => false
};
}
}
public override AstNode VisitExprFilter(AstExprFilter node)
{
var optimizedNode = base.VisitExprFilter(node);
if (optimizedNode is AstExprFilter exprFilter &&
exprFilter.Expression is AstUnaryExpression unaryExpression &&
unaryExpression.Operator == AstUnaryOperator.AnyElementTrue &&
unaryExpression.Arg is AstMapExpression mapExpression &&
mapExpression.Input is AstConstantExpression inputConstant &&
inputConstant.Value is BsonArray inputArrayValue &&
mapExpression.In is AstBinaryExpression inBinaryExpression &&
inBinaryExpression.Operator == AstBinaryOperator.Eq &&
TryGetBinaryExpressionArguments(inBinaryExpression, out AstFieldPathExpression fieldPathExpression, out AstVarExpression varExpression) &&
fieldPathExpression.Path.Length > 1 && fieldPathExpression.Path[0] == '$' && fieldPathExpression.Path[1] != '$' &&
varExpression == mapExpression.As)
{
// { $expr : { $anyElementTrue : { $map : { input : <constantArray>, as : "<var>", in : { $eq : ["$<dottedFieldName>", "$$<var>"] } } } } }
// => { "<dottedFieldName>" : { $in : <constantArray> } }
return AstFilter.In(AstFilter.Field(fieldPathExpression.Path.Substring(1)), inputArrayValue);
}
return optimizedNode;
static bool TryGetBinaryExpressionArguments<T1, T2>(AstBinaryExpression binaryExpression, out T1 arg1, out T2 arg2)
where T1 : AstNode
where T2 : AstNode
{
if (binaryExpression.Arg1 is T1 arg1AsT1 && binaryExpression.Arg2 is T2 arg2AsT2)
{
arg1 = arg1AsT1;
arg2 = arg2AsT2;
return true;
}
if (binaryExpression.Arg1 is T2 arg1AsT2 && binaryExpression.Arg1 is T1 arg2AsT1)
{
arg1 = arg2AsT1;
arg2 = arg1AsT2;
return true;
}
arg1 = null;
arg2 = null;
return false;
}
}
public override AstNode VisitFieldOperationFilter(AstFieldOperationFilter node)
{
node = (AstFieldOperationFilter)base.VisitFieldOperationFilter(node);
if (node.Field.Path != "@<elem>")
{
// { field : { $eq : value } } => { field : value } where value is not a regex
if (IsFieldEqValue(node, out var value))
{
var impliedOperation = new AstImpliedOperationFilterOperation(value);
return new AstFieldOperationFilter(node.Field, impliedOperation);
}
// { field : { $regex : "pattern", $options : "options" } } => { field : /pattern/options }
if (IsFieldRegex(node, out var regex))
{
var impliedOperation = new AstImpliedOperationFilterOperation(regex);
return new AstFieldOperationFilter(node.Field, impliedOperation);
}
// { field : { $not : { $regex : "pattern", $options : "options" } } } => { field : { $not : /pattern/options } }
if (IsFieldNotRegex(node, out regex))
{
var notImpliedOperation = new AstNotFilterOperation(new AstImpliedOperationFilterOperation(regex));
return new AstFieldOperationFilter(node.Field, notImpliedOperation);
}
// { field : { $elemMatch : { $eq : value } } } => { field : value } where value is not regex
if (IsFieldElemMatchEqValue(node, out value))
{
var impliedOperation = new AstImpliedOperationFilterOperation(value);
return new AstFieldOperationFilter(node.Field, impliedOperation);
}
// { field : { $elemMatch : { $regex : "pattern", $options : "options" } } } => { field : /pattern/options }
if (IsFieldElemMatchRegex(node, out regex))
{
var impliedOperation = new AstImpliedOperationFilterOperation(regex);
return new AstFieldOperationFilter(node.Field, impliedOperation);
}
// { field : { $elemMatch : { $not : { $regex : "pattern", $options : "options" } } } } => { field : { $elemMatch : { $not : /pattern/options } } }
if (IsFieldElemMatchNotRegex(node, out var elemField, out regex))
{
var notRegexOperation = new AstNotFilterOperation(new AstImpliedOperationFilterOperation(regex));
var elemFilter = new AstFieldOperationFilter(elemField, notRegexOperation);
var elemMatchOperation = new AstElemMatchFilterOperation(elemFilter);
return new AstFieldOperationFilter(node.Field, elemMatchOperation);
}
// { field : { $not : { $elemMatch : { $eq : value } } } } => { field : { $ne : value } } where value is not regex
if (IsFieldNotElemMatchEqValue(node, out value))
{
var impliedOperation = new AstComparisonFilterOperation(AstComparisonFilterOperator.Ne, value);
return new AstFieldOperationFilter(node.Field, impliedOperation);
}
// { field : { $not : { $elemMatch : { $regex : "pattern", $options : "options" } } } } => { field : { $not : /pattern/options } }
if (IsFieldNotElemMatchRegex(node, out regex))
{
var notImpliedOperation = new AstNotFilterOperation(new AstImpliedOperationFilterOperation(regex));
return new AstFieldOperationFilter(node.Field, notImpliedOperation);
}
}
return node;
static bool IsFieldEqValue(AstFieldOperationFilter node, out BsonValue value)
{
// { field : { $eq : value } } where value is not a a regex
if (node.Operation is AstComparisonFilterOperation comparisonOperation &&
comparisonOperation.Operator == AstComparisonFilterOperator.Eq &&
comparisonOperation.Value.BsonType != BsonType.RegularExpression)
{
value = comparisonOperation.Value;
return true;
}
value = null;
return false;
}
static bool IsFieldRegex(AstFieldOperationFilter node, out BsonRegularExpression regex)
{
// { field : { $regex : "pattern", $options : "options" } }
if (node.Operation is AstRegexFilterOperation regexOperation)
{
regex = new BsonRegularExpression(regexOperation.Pattern, regexOperation.Options);
return true;
}
regex = null;
return false;
}
static bool IsFieldNotRegex(AstFieldOperationFilter node, out BsonRegularExpression regex)
{
// { field : { $not : { $regex : "pattern", $options : "options" } } }
if (node.Operation is AstNotFilterOperation notOperation &&
notOperation.Operation is AstRegexFilterOperation regexOperation)
{
regex = new BsonRegularExpression(regexOperation.Pattern, regexOperation.Options);
return true;
}
regex = null;
return false;
}
static bool IsFieldElemMatchEqValue(AstFieldOperationFilter node, out BsonValue value)
{
// { field : { $elemMatch : { $eq : value } } } where value is not regex
if (node.Operation is AstElemMatchFilterOperation elemMatchOperation &&
elemMatchOperation.Filter is AstFieldOperationFilter elemFilter &&
elemFilter.Field.Path == "@<elem>" &&
elemFilter.Operation is AstComparisonFilterOperation comparisonOperation &&
comparisonOperation.Operator == AstComparisonFilterOperator.Eq &&
comparisonOperation.Value.BsonType != BsonType.RegularExpression)
{
value = comparisonOperation.Value;
return true;
}
value = null;
return false;
}
static bool IsFieldElemMatchRegex(AstFieldOperationFilter node, out BsonRegularExpression regex)
{
// { field : { $elemMatch : { $regex : "pattern", $options : "options" } } }
if (node.Operation is AstElemMatchFilterOperation elemMatchOperation &&
elemMatchOperation.Filter is AstFieldOperationFilter elemFilter &&
elemFilter.Field.Path == "@<elem>" &&
elemFilter.Operation is AstRegexFilterOperation regexOperation)
{
regex = new BsonRegularExpression(regexOperation.Pattern, regexOperation.Options);
return true;
}
regex = null;
return false;
}
static bool IsFieldElemMatchNotRegex(AstFieldOperationFilter node, out AstFilterField elemField, out BsonRegularExpression regex)
{
// { field : { $elemMatch : { $not : { $regex : "pattern", $options : "options" } } } }
if (node.Operation is AstElemMatchFilterOperation elemMatch &&
elemMatch.Filter is AstFieldOperationFilter elemFilter &&
elemFilter.Field.Path == "@<elem>" &&
elemFilter.Operation is AstNotFilterOperation notOperation &&
notOperation.Operation is AstRegexFilterOperation regexOperation)
{
elemField = elemFilter.Field;
regex = new BsonRegularExpression(regexOperation.Pattern, regexOperation.Options);
return true;
}
elemField = null;
regex = null;
return false;
}
static bool IsFieldNotElemMatchEqValue(AstFieldOperationFilter node, out BsonValue value)
{
// { field : { $not : { $elemMatch : { $eq : value } } } } where value is not regex
if (node.Operation is AstNotFilterOperation notFilterOperation &&
notFilterOperation.Operation is AstElemMatchFilterOperation elemMatchOperation &&
elemMatchOperation.Filter is AstFieldOperationFilter elemFilter &&
elemFilter.Field.Path == "@<elem>" &&
elemFilter.Operation is AstComparisonFilterOperation comparisonOperation &&
comparisonOperation.Operator == AstComparisonFilterOperator.Eq &&
comparisonOperation.Value.BsonType != BsonType.RegularExpression)
{
value = comparisonOperation.Value;
return true;
}
value = null;
return false;
}
static bool IsFieldNotElemMatchRegex(AstFieldOperationFilter node, out BsonRegularExpression regex)
{
// { field : { $not : { $elemMatch : { $regex : "pattern", $options : "options" } } } }
if (node.Operation is AstNotFilterOperation notFilterOperation &&
notFilterOperation.Operation is AstElemMatchFilterOperation elemMatchOperation &&
elemMatchOperation.Filter is AstFieldOperationFilter elemFilter &&
elemFilter.Field.Path == "@<elem>" &&
elemFilter.Operation is AstRegexFilterOperation regexOperation)
{
regex = new BsonRegularExpression(regexOperation.Pattern, regexOperation.Options);
return true;
}
regex = null;
return false;
}
}
public override AstNode VisitFilterExpression(AstFilterExpression node)
{
var inputExpression = VisitAndConvert(node.Input);
var condExpression = VisitAndConvert(node.Cond);
var limitExpression = VisitAndConvert(node.Limit);
if (condExpression is AstConstantExpression condConstantExpression &&
condConstantExpression.Value is BsonBoolean condBsonBoolean)
{
if (condBsonBoolean.Value)
{
// { $filter : { input : <input>, as : "x", cond : true } } => <input>
if (limitExpression == null)
{
return inputExpression;
}
}
else
{
// { $filter : { input : <input>, as : "x", cond : false, optional-limit } } => []
return AstExpression.Constant(new BsonArray());
}
}
return node.Update(inputExpression, condExpression, limitExpression);
}
public override AstNode VisitGetFieldExpression(AstGetFieldExpression node)
{
if (TrySimplifyAsFieldPath(node, out var simplified))
{
return simplified;
}
if (TrySimplifyAsLet(node, out simplified))
{
return simplified;
}
return base.VisitGetFieldExpression(node);
// { $getField : { field : "y", input : "$x" } } => "$x.y"
static bool TrySimplifyAsFieldPath(AstGetFieldExpression node, out AstExpression simplified)
{
if (node.CanBeConvertedToFieldPath())
{
var path = node.ConvertToFieldPath();
simplified = AstExpression.FieldPath(path);
return true;
}
simplified = null;
return false;
}
// { $getField : { field : "x", input : <input> } } => { $let : { vars : { this : <input> }, in : "$$this.x" } }
bool TrySimplifyAsLet(AstGetFieldExpression node, out AstExpression simplified)
{
if (node.HasSafeFieldName(out var fieldName))
{
var simplifiedInput = VisitAndConvert(node.Input);
var var = AstExpression.Var("this");
var binding = AstExpression.VarBinding(var, simplifiedInput);
simplified = AstExpression.Let(binding, AstExpression.FieldPath($"$$this.{fieldName}"));
return true;
}
simplified = null;
return false;
}
}
public override AstNode VisitLetExpression(AstLetExpression node)
{
node = (AstLetExpression)base.VisitLetExpression(node);
// { $let : { vars : { var : expr }, in : "$$var" } } => expr
if (node.Vars.Count == 1 &&
node.Vars[0].Var.Name is string varName &&
node.In is AstVarExpression varExpression &&
varExpression.Name == varName)
{
return node.Vars[0].Value;
}
return node;
}
public override AstNode VisitMapExpression(AstMapExpression node)
{
// { $map : { input : <input>, as : "v", in : "$$v.x" } } => { $getField : { field : "x", input : <input> } }
if (node.Input is AstGetFieldExpression inputGetField &&
node.In is AstGetFieldExpression inGetField)
{
if (UltimateGetFieldInput(inGetField) == node.As)
{
var simplified = AstNodeReplacer.Replace(node.In, (node.As, node.Input));
return Visit(simplified);
}
}
if (node.In is AstComputedDocumentExpression inComputedDocumentExpression &&
inComputedDocumentExpression.Fields.All(f => f.Value is AstGetFieldExpression getFieldExpression && getFieldExpression.Input == node.As && getFieldExpression.CanBeConvertedToFieldPath()))
{
// { $map : { input : { $map : { input : <input>, as : "y", in : { A : "$$y.FieldA" } } }, as: "v", in : { B : '$$v.A' } } } => { $map : { input : <input>, as: "v", in : { B : "$$v.FieldA" } } }
if (node.Input is AstMapExpression inputMapExpression &&
inputMapExpression.In is AstComputedDocumentExpression innerInComputedDocumentExpression)
{
var simplified = AstExpression.Map(
inputMapExpression.Input,
inputMapExpression.As,
AstExpression.ComputedDocument(inComputedDocumentExpression.Fields.Select(f => RemapField(f, node.As.Name, innerInComputedDocumentExpression.Fields))));
return Visit(simplified);
}
// { $map : { input : [{ A: "$$ROOT.FieldA" }], as : "v", in: { B : "$$v.A" } } } => [{ B : "$FieldA }]
if (node.Input is AstComputedArrayExpression inputArrayExpression &&
inputArrayExpression.Items.All(i => i is AstComputedDocumentExpression))
{
var simplified = AstExpression.ComputedArray(inputArrayExpression.Items.Select(i =>
AstExpression.ComputedDocument(inComputedDocumentExpression.Fields.Select(f => RemapField(f, node.As.Name, ((AstComputedDocumentExpression)i).Fields)))));
return Visit(simplified);
}
}
return base.VisitMapExpression(node);
static AstComputedField RemapField(AstComputedField field, string @as, IEnumerable<AstComputedField> innerFields)
{
var fieldPath = ((AstGetFieldExpression)field.Value).ConvertToFieldPath().Replace($"$${@as}.", string.Empty);
var innerField = innerFields.Single(f => f.Path == fieldPath);
return AstExpression.ComputedField(field.Path, innerField.Value);
}
static AstExpression UltimateGetFieldInput(AstGetFieldExpression getField)
{
if (getField.Input is AstGetFieldExpression nestedInputGetField)
{
return UltimateGetFieldInput(nestedInputGetField);
}
return getField.Input;
}
}
public override AstNode VisitNotFilterOperation(AstNotFilterOperation node)
{
if (node.Operation is AstExistsFilterOperation existsFilterOperation)
{
return new AstExistsFilterOperation(!existsFilterOperation.Exists);
}
return base.VisitNotFilterOperation(node);
}
public override AstNode VisitPipeline(AstPipeline node)
{
var stages = VisitAndConvert(node.Stages);
// { $match : { } } => remove redundant stage
if (stages.Any(stage => IsMatchEverythingStage(stage)))
{
stages = stages.Where(stage => !IsMatchEverythingStage(stage)).AsReadOnlyList();
}
return node.Update(stages);
static bool IsMatchEverythingStage(AstStage stage)
{
return
stage is AstMatchStage matchStage &&
matchStage.Filter is AstMatchesEverythingFilter;
}
}
public override AstNode VisitSliceExpression(AstSliceExpression node)
{
node = (AstSliceExpression)base.VisitSliceExpression(node);
var array = node.Array;
var position = node.Position ?? 0; // map null to zero
var n = node.N;
if (position.IsZero() && n.IsMaxInt32())
{
// { $slice : [array, 0, maxint] } => array
return array;
}
if (array is AstConstantExpression arrayConstant &&
arrayConstant.Value is BsonArray bsonArrayConstant &&
position.IsInt32Constant(out var positionValue) && positionValue >= 0 &&
n.IsInt32Constant(out var nValue) && nValue >= 0)
{
// { slice : [array, position, n] } => array.Skip(position).Take(n) when all arguments are non-negative constants
return AstExpression.Constant(new BsonArray(bsonArrayConstant.Skip(positionValue).Take(nValue)));
}
if (array is AstSliceExpression inner &&
(inner.Position ?? 0).IsInt32Constant(out var innerPosition) && innerPosition >= 0 &&
inner.N.IsInt32Constant(out var innerN) && innerN >= 0 &&
position.IsInt32Constant(out var outerPosition) && outerPosition >= 0 &&
n.IsInt32Constant(out var outerN) && outerN >= 0)
{
// the following simplifcations are only valid when all position and n values are known to be non-negative (so they have to be constants)
// { $slice : [{ $slice : [inner.Array, innerPosition, maxint] }, outerPosition, maxint] } => { $slice : [inner.Array, innerPosition + outerPosition, maxint] }
// { $slice : [{ $slice : [inner.Array, innerPosition, maxint] }, outerPosition, outerN] } => { $slice : [inner.Array, innerPosition + outerPosition, outerN] }
// { $slice : [{ $slice : [inner.Array, innerPosition, innerN] }, outerPosition, maxint] } => { $slice : [inner.Array, innerPosition + outerPosition, max(innerN - outerPosition, 0)] }
// { $slice : [{ $slice : [inner.Array, innerPosition, innerN] }, outerPosition, outerN] } => { $slice : [inner.Array, innerPosition + outerPosition, min(max(innerN - outerPosition, 0), outerN)] }
var combinedPosition = AstExpression.Add(innerPosition, outerPosition);
var combinedN = (innerN, outerN) switch
{
(int.MaxValue, int.MaxValue) => int.MaxValue, // check whether both are int.MaxValue before checking one at a time
(int.MaxValue, _) => outerN,
(_, int.MaxValue) => Math.Max(innerN - outerPosition, 0),
_ => Math.Min(Math.Max(innerN - outerPosition, 0), outerN)
};
return AstExpression.Slice(inner.Array, combinedPosition, combinedN);
}
return node;
}
public override AstNode VisitUnaryExpression(AstUnaryExpression node)
{
var arg = VisitAndConvert(node.Arg);
// { $first : <arg> } => { $arrayElemAt : [<arg>, 0] } (or -1 for $last)
if (node.Operator == AstUnaryOperator.First || node.Operator == AstUnaryOperator.Last)
{
var index = node.Operator == AstUnaryOperator.First ? 0 : -1;
return AstExpression.ArrayElemAt(arg, index);
}
// { $not : booleanConstant } => !booleanConstant
if (node.Operator is AstUnaryOperator.Not &&
arg is AstConstantExpression argConstantExpression &&
argConstantExpression.Value is BsonBoolean argBsonBoolean)
{
return AstExpression.Constant(!argBsonBoolean.Value);
}
// { $not : { $eq : [expr1, expr2] } } => { $ne : [expr1, expr2] }
// { $not : { $ne : [expr1, expr2] } } => { $eq : [expr1, expr2] }
if (node.Operator is AstUnaryOperator.Not &&
arg is AstBinaryExpression argBinaryExpression &&
argBinaryExpression.Operator is AstBinaryOperator.Eq or AstBinaryOperator.Ne)
{
var oppositeComparisonOperator = argBinaryExpression.Operator == AstBinaryOperator.Eq ? AstBinaryOperator.Ne : AstBinaryOperator.Eq;
return AstExpression.Binary(oppositeComparisonOperator, argBinaryExpression.Arg1, argBinaryExpression.Arg2);
}
// { $arrayToObject : [[{ k : 'A', v : '$A' }, { k : 'B', v : '$B' }]] } => { A : '$A', B : '$B' }
if (node.Operator is AstUnaryOperator.ArrayToObject &&
arg is AstComputedArrayExpression computedArrayExpression &&
computedArrayExpression.Items.All(
i => i is AstComputedDocumentExpression computedDocumentExpression &&
computedDocumentExpression.Fields.FirstOrDefault(f => f.Path == "k")?.Value is AstConstantExpression &&
computedDocumentExpression.Fields.Any(f => f.Path == "v"))
)
{
var fields = computedArrayExpression.Items.Select(KeyValuePairDocumentToComputedField);
return AstExpression.ComputedDocument(fields);
}
return node.Update(arg);
static AstComputedField KeyValuePairDocumentToComputedField(AstExpression expression)
{
var documentExpression = (AstComputedDocumentExpression)expression;
var keyExpression = documentExpression.Fields.First(f => f.Path == "k").Value;
var valueExpression = documentExpression.Fields.First(f => f.Path == "v").Value;
return AstExpression.ComputedField(((AstConstantExpression)keyExpression).Value.AsString, valueExpression);
}
}
}
}