summaryrefslogtreecommitdiff
path: root/src/mongo/db/pipeline/abt/match_expression_visitor.cpp
blob: 70be6fd3651c2f79d27f2859c509e6cb07b801ba (plain)
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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
/**
 *    Copyright (C) 2022-present MongoDB, Inc.
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the Server Side Public License, version 1,
 *    as published by MongoDB, Inc.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    Server Side Public License for more details.
 *
 *    You should have received a copy of the Server Side Public License
 *    along with this program. If not, see
 *    <http://www.mongodb.com/licensing/server-side-public-license>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the Server Side Public License in all respects for
 *    all of the code used other than as permitted herein. If you modify file(s)
 *    with this exception, you may extend this exception to your version of the
 *    file(s), but you are not obligated to do so. If you do not wish to do so,
 *    delete this exception statement from your version. If you delete this
 *    exception statement from all source files in the program, then also delete
 *    it in the license file.
 */

#include "mongo/db/pipeline/abt/match_expression_visitor.h"
#include "mongo/db/matcher/expression_always_boolean.h"
#include "mongo/db/matcher/expression_array.h"
#include "mongo/db/matcher/expression_expr.h"
#include "mongo/db/matcher/expression_geo.h"
#include "mongo/db/matcher/expression_internal_bucket_geo_within.h"
#include "mongo/db/matcher/expression_internal_expr_comparison.h"
#include "mongo/db/matcher/expression_leaf.h"
#include "mongo/db/matcher/expression_text.h"
#include "mongo/db/matcher/expression_text_noop.h"
#include "mongo/db/matcher/expression_tree.h"
#include "mongo/db/matcher/expression_type.h"
#include "mongo/db/matcher/expression_visitor.h"
#include "mongo/db/matcher/expression_where.h"
#include "mongo/db/matcher/expression_where_noop.h"
#include "mongo/db/matcher/match_expression_walker.h"
#include "mongo/db/matcher/schema/expression_internal_schema_all_elem_match_from_index.h"
#include "mongo/db/matcher/schema/expression_internal_schema_allowed_properties.h"
#include "mongo/db/matcher/schema/expression_internal_schema_cond.h"
#include "mongo/db/matcher/schema/expression_internal_schema_eq.h"
#include "mongo/db/matcher/schema/expression_internal_schema_fmod.h"
#include "mongo/db/matcher/schema/expression_internal_schema_match_array_index.h"
#include "mongo/db/matcher/schema/expression_internal_schema_max_items.h"
#include "mongo/db/matcher/schema/expression_internal_schema_max_length.h"
#include "mongo/db/matcher/schema/expression_internal_schema_max_properties.h"
#include "mongo/db/matcher/schema/expression_internal_schema_min_items.h"
#include "mongo/db/matcher/schema/expression_internal_schema_min_length.h"
#include "mongo/db/matcher/schema/expression_internal_schema_min_properties.h"
#include "mongo/db/matcher/schema/expression_internal_schema_object_match.h"
#include "mongo/db/matcher/schema/expression_internal_schema_root_doc_eq.h"
#include "mongo/db/matcher/schema/expression_internal_schema_unique_items.h"
#include "mongo/db/matcher/schema/expression_internal_schema_xor.h"
#include "mongo/db/pipeline/abt/agg_expression_visitor.h"
#include "mongo/db/pipeline/abt/expr_algebrizer_context.h"
#include "mongo/db/pipeline/abt/utils.h"
#include "mongo/db/query/optimizer/utils/utils.h"

namespace mongo::optimizer {

class ABTMatchExpressionPreVisitor : public SelectiveMatchExpressionVisitorBase<true> {
    using SelectiveMatchExpressionVisitorBase<true>::visit;

public:
    ABTMatchExpressionPreVisitor(ExpressionAlgebrizerContext& ctx) : _ctx(ctx) {}

    void visit(const ElemMatchObjectMatchExpression* expr) override {
        _ctx.enterElemMatch(expr->matchType());
    }

    void visit(const ElemMatchValueMatchExpression* expr) override {
        _ctx.enterElemMatch(expr->matchType());
    }

private:
    ExpressionAlgebrizerContext& _ctx;
};

class ABTMatchExpressionVisitor : public MatchExpressionConstVisitor {
public:
    ABTMatchExpressionVisitor(ExpressionAlgebrizerContext& ctx, const bool allowAggExpressions)
        : _allowAggExpressions(allowAggExpressions), _ctx(ctx) {}

    void visit(const AlwaysFalseMatchExpression* expr) override {
        generateBoolConstant(false);
    }

    void visit(const AlwaysTrueMatchExpression* expr) override {
        generateBoolConstant(true);
    }

    void visit(const AndMatchExpression* expr) override {
        visitAndOrExpression<PathComposeM, true>(expr);
    }

    void visit(const BitsAllClearMatchExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const BitsAllSetMatchExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const BitsAnyClearMatchExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const BitsAnySetMatchExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const ElemMatchObjectMatchExpression* expr) override {
        generateElemMatch<false /*isValueElemMatch*/>(expr);
        _ctx.exitElemMatch();
    }

    void visit(const ElemMatchValueMatchExpression* expr) override {
        generateElemMatch<true /*isValueElemMatch*/>(expr);
        _ctx.exitElemMatch();
    }

    void visit(const EqualityMatchExpression* expr) override {
        generateSimpleComparison(expr, Operations::Eq);
    }

    void visit(const ExistsMatchExpression* expr) override {
        assertSupportedPathExpression(expr);

        ABT result = make<PathDefault>(Constant::boolean(false));
        if (shouldGeneratePath(expr)) {
            result = translateFieldRef(*(expr->fieldRef()), std::move(result));
        }
        _ctx.push(std::move(result));
    }

    void visit(const ExprMatchExpression* expr) override {
        uassert(6624246, "Cannot generate an agg expression in this context", _allowAggExpressions);

        ABT result = generateAggExpression(
            expr->getExpression().get(), _ctx.getRootProjection(), _ctx.getUniqueIdPrefix());

        if (auto filterPtr = result.cast<EvalFilter>();
            filterPtr != nullptr && filterPtr->getInput() == _ctx.getRootProjVar()) {
            // If we have an EvalFilter, just return the path.
            _ctx.push(std::move(filterPtr->getPath()));
        } else {
            _ctx.push<PathConstant>(std::move(result));
        }
    }

    void visit(const GTEMatchExpression* expr) override {
        generateSimpleComparison(expr, Operations::Gte);
    }

    void visit(const GTMatchExpression* expr) override {
        generateSimpleComparison(expr, Operations::Gt);
    }

    void visit(const GeoMatchExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const GeoNearMatchExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const InMatchExpression* expr) override {
        uassert(ErrorCodes::InternalErrorNotSupported,
                "$in with regexes is not supported.",
                expr->getRegexes().empty());

        assertSupportedPathExpression(expr);

        const auto& equalities = expr->getEqualities();

        // $in with an empty equalities list matches nothing; replace with constant false.
        if (equalities.empty()) {
            generateBoolConstant(false);
            return;
        }

        ABT result = make<PathIdentity>();

        const auto [tagTraverse, valTraverse] = sbe::value::makeNewArray();
        sbe::value::ValueGuard arrGuard{tagTraverse, valTraverse};
        auto arrTraversePtr = sbe::value::getArrayView(valTraverse);
        arrTraversePtr->reserve(equalities.size());

        const auto [tagArraysOnly, valArraysOnly] = sbe::value::makeNewArray();
        sbe::value::ValueGuard arrOnlyGuard{tagArraysOnly, valArraysOnly};
        auto arraysOnlyPtr = sbe::value::getArrayView(valArraysOnly);
        bool addNullPathDefault = false;
        arraysOnlyPtr->reserve(equalities.size());

        for (const auto& pred : equalities) {
            const auto [tag, val] = convertFrom(Value(pred));
            arrTraversePtr->push_back(tag, val);

            if (tag == sbe::value::TypeTags::Null) {
                addNullPathDefault = true;
            } else if (tag == sbe::value::TypeTags::Array) {
                const auto [tag2, val2] = sbe::value::copyValue(tag, val);
                arraysOnlyPtr->push_back(tag2, val2);
            }
        }

        // If there is only one term in the match expression, we don't need to use EqMember
        if (arrTraversePtr->size() == 1) {
            const auto [tagSingle, valSingle] = sbe::value::copyValue(
                arrTraversePtr->getAt(0).first, arrTraversePtr->getAt(0).second);
            result = make<PathCompare>(Operations::Eq, make<Constant>(tagSingle, valSingle));
        } else {
            result =
                make<PathCompare>(Operations::EqMember, make<Constant>(tagTraverse, valTraverse));
            arrGuard.reset();
        }

        if (addNullPathDefault) {
            maybeComposePath<PathComposeA>(result, make<PathDefault>(Constant::boolean(true)));
        }

        // Do not insert a traverse if within an $elemMatch; traversal will be handled by the
        // $elemMatch expression itself.
        if (shouldGeneratePath(expr)) {
            // When the path we are comparing is a path to an array, the comparison is
            // considered true if it evaluates to true for the array itself or for any of the
            // array’s elements. 'result' evaluates comparison on the array elements, and
            // 'arraysOnly' evaluates the comparison on the array itself.
            result = make<PathTraverse>(std::move(result), PathTraverse::kSingleLevel);

            if (arraysOnlyPtr->size() == 1) {
                const auto [tagSingle, valSingle] = sbe::value::copyValue(
                    arraysOnlyPtr->getAt(0).first, arraysOnlyPtr->getAt(0).second);
                maybeComposePath<PathComposeA>(
                    result,
                    make<PathCompare>(Operations::Eq, make<Constant>(tagSingle, valSingle)));
            } else if (arraysOnlyPtr->size() > 0) {
                maybeComposePath<PathComposeA>(
                    result,
                    make<PathCompare>(Operations::EqMember,
                                      make<Constant>(tagArraysOnly, valArraysOnly)));
                arrOnlyGuard.reset();
            }
            result = translateFieldRef(*(expr->fieldRef()), std::move(result));
        }
        _ctx.push(std::move(result));
    }

    void visit(const InternalBucketGeoWithinMatchExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const InternalExprEqMatchExpression* expr) override {
        // Ignored. Translate to "true".
        _ctx.push(make<PathConstant>(Constant::boolean(true)));
    }

    void visit(const InternalExprGTMatchExpression* expr) override {
        // Ignored. Translate to "true".
        _ctx.push(make<PathConstant>(Constant::boolean(true)));
    }

    void visit(const InternalExprGTEMatchExpression* expr) override {
        // Ignored. Translate to "true".
        _ctx.push(make<PathConstant>(Constant::boolean(true)));
    }

    void visit(const InternalExprLTMatchExpression* expr) override {
        // Ignored. Translate to "true".
        _ctx.push(make<PathConstant>(Constant::boolean(true)));
    }

    void visit(const InternalExprLTEMatchExpression* expr) override {
        // Ignored. Translate to "true".
        _ctx.push(make<PathConstant>(Constant::boolean(true)));
    }

    void visit(const InternalSchemaAllElemMatchFromIndexMatchExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const InternalSchemaAllowedPropertiesMatchExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const InternalSchemaBinDataEncryptedTypeExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const InternalSchemaBinDataFLE2EncryptedTypeExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const InternalSchemaBinDataSubTypeExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const InternalSchemaCondMatchExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const InternalSchemaEqMatchExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const InternalSchemaFmodMatchExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const InternalSchemaMatchArrayIndexMatchExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const InternalSchemaMaxItemsMatchExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const InternalSchemaMaxLengthMatchExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const InternalSchemaMaxPropertiesMatchExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const InternalSchemaMinItemsMatchExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const InternalSchemaMinLengthMatchExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const InternalSchemaMinPropertiesMatchExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const InternalSchemaObjectMatchExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const InternalSchemaRootDocEqMatchExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const InternalSchemaTypeExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const InternalSchemaUniqueItemsMatchExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const InternalSchemaXorMatchExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const LTEMatchExpression* expr) override {
        generateSimpleComparison(expr, Operations::Lte);
    }

    void visit(const LTMatchExpression* expr) override {
        generateSimpleComparison(expr, Operations::Lt);
    }

    void visit(const ModMatchExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const NorMatchExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const NotMatchExpression* expr) override {
        ABT result = _ctx.pop();

        // If this $not expression is a child of an $elemMatch, then we need to use a PathLambda to
        // ensure that the value stream (variable) corresponding to the inner path element is passed
        // into the inner EvalFilter.
        //
        // Examples:
        // find({"a.b": {$not: {$eq: 1}}}): The input into the not expression are documents from the
        // Scan. The EvalFilter expression will encapsulate the "a.b" path traversal.
        //
        // find({"a": {$elemMatch: {b: {$not: {$eq: 1}}}}}): The outer EvalFilter expression
        // encapsulates the "a" path traversal. However, we need the input to the not expression to
        // be the value of the "b" field, rather than those of "a". We use the PathLambda expression
        // to achieve this.
        if (_ctx.inElemMatch()) {
            auto notProjName = _ctx.getNextId("not");
            _ctx.push(make<PathLambda>(make<LambdaAbstraction>(
                notProjName,
                make<UnaryOp>(Operations::Not,
                              make<EvalFilter>(std::move(result), make<Variable>(notProjName))))));
            return;
        }
        _ctx.push(make<PathConstant>(make<UnaryOp>(
            Operations::Not,
            make<EvalFilter>(std::move(result), make<Variable>(_ctx.getRootProjection())))));
    }

    void visit(const OrMatchExpression* expr) override {
        visitAndOrExpression<PathComposeA, false>(expr);
    }

    void visit(const RegexMatchExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const SizeMatchExpression* expr) override {
        assertSupportedPathExpression(expr);

        const std::string lambdaProjName = _ctx.getNextId("lambda_sizeMatch");
        ABT result = make<PathLambda>(make<LambdaAbstraction>(
            lambdaProjName,
            make<BinaryOp>(
                Operations::Eq,
                make<FunctionCall>("getArraySize", makeSeq(make<Variable>(lambdaProjName))),
                Constant::int64(expr->getData()))));

        if (shouldGeneratePath(expr)) {
            result = translateFieldRef(*(expr->fieldRef()), std::move(result));
        }
        _ctx.push(std::move(result));
    }

    void visit(const TextMatchExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const TextNoOpMatchExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const TwoDPtInAnnulusExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const TypeMatchExpression* expr) override {
        assertSupportedPathExpression(expr);

        const std::string lambdaProjName = _ctx.getNextId("lambda_typeMatch");
        ABT result = make<PathLambda>(make<LambdaAbstraction>(
            lambdaProjName,
            make<FunctionCall>("typeMatch",
                               makeSeq(make<Variable>(lambdaProjName),
                                       Constant::int32(expr->typeSet().getBSONTypeMask())))));

        if (shouldGeneratePath(expr)) {
            result = make<PathTraverse>(std::move(result), PathTraverse::kSingleLevel);
            if (expr->typeSet().hasType(BSONType::Array)) {
                // If we are testing against array type, insert a comparison against the
                // non-traversed path (the array itself if we have one).
                result = make<PathComposeA>(make<PathArr>(), std::move(result));
            }

            result = translateFieldRef(*(expr->fieldRef()), std::move(result));
        }
        _ctx.push(std::move(result));
    }

    void visit(const WhereMatchExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const WhereNoOpMatchExpression* expr) override {
        unsupportedExpression(expr);
    }

    void visit(const BetweenMatchExpression* expr) override {
        unsupportedExpression(expr);
    }

private:
    void generateBoolConstant(const bool value) {
        _ctx.push<PathConstant>(Constant::boolean(value));
    }

    template <bool isValueElemMatch>
    void generateElemMatch(const ArrayMatchingMatchExpression* expr) {
        assertSupportedPathExpression(expr);

        // Returns true if at least one sub-objects matches the condition.

        const size_t childCount = expr->numChildren();
        if (childCount == 0) {
            _ctx.push(Constant::boolean(true));
        }

        _ctx.ensureArity(childCount);
        ABT result = _ctx.pop();
        for (size_t i = 1; i < childCount; i++) {
            maybeComposePath(result, _ctx.pop());
        }
        if constexpr (!isValueElemMatch) {
            // Make sure we consider only objects or arrays as elements of the array.
            maybeComposePath(result, make<PathComposeA>(make<PathObj>(), make<PathArr>()));
        }
        result = make<PathTraverse>(std::move(result), PathTraverse::kSingleLevel);

        // Make sure we consider only arrays fields on the path.
        maybeComposePath(result, make<PathArr>());

        if (shouldGeneratePath(expr)) {
            result = translateFieldRef(*(expr->fieldRef()), std::move(result));
        }

        _ctx.push(std::move(result));
    }

    void assertSupportedPathExpression(const PathMatchExpression* expr) {
        uassert(ErrorCodes::InternalErrorNotSupported,
                "Expression contains a numeric path component",
                !FieldRef(expr->path()).hasNumericPathComponents());
    }

    void generateSimpleComparison(const ComparisonMatchExpressionBase* expr, const Operations op) {
        assertSupportedPathExpression(expr);

        auto [tag, val] = convertFrom(Value(expr->getData()));
        ABT result = make<PathCompare>(op, make<Constant>(tag, val));

        bool tagNullMatchMissingField =
            tag == sbe::value::TypeTags::Null && (op == Operations::Lte || op == Operations::Gte);

        switch (op) {
            case Operations::Lt:
            case Operations::Lte: {
                auto&& [constant, inclusive] = getMinMaxBoundForType(true /*isMin*/, tag);
                if (constant) {
                    maybeComposePath(result,
                                     make<PathCompare>(inclusive ? Operations::Gte : Operations::Gt,
                                                       std::move(constant.get())));
                }
                // Handle null and missing semantics
                // find({a: {$lt: MaxKey()}}) matches {a: null} and {b: 1}
                // find({a: {$lte: null}}) matches {a: null} and {b: 1})
                if (tag == sbe::value::TypeTags::MaxKey || tagNullMatchMissingField) {
                    maybeComposePath<PathComposeA>(result,
                                                   make<PathDefault>(Constant::boolean(true)));
                }
                break;
            }

            case Operations::Gt:
            case Operations::Gte: {
                auto&& [constant, inclusive] = getMinMaxBoundForType(false /*isMin*/, tag);
                if (constant) {
                    maybeComposePath(result,
                                     make<PathCompare>(inclusive ? Operations::Lte : Operations::Lt,
                                                       std::move(constant.get())));
                }
                // Handle null and missing semantics
                // find({a: {$gt: MinKey()}}) matches {a: null} and {b: 1}
                // find({a: {$gte: null}}) matches {a: null} and {b: 1})
                if (tag == sbe::value::TypeTags::MinKey || tagNullMatchMissingField) {
                    maybeComposePath<PathComposeA>(result,
                                                   make<PathDefault>(Constant::boolean(true)));
                }
                break;
            }

            case Operations::Eq: {
                if (tag == sbe::value::TypeTags::Null) {
                    // Handle null and missing semantics. Matching against null also implies
                    // matching against missing.
                    result = make<PathComposeA>(make<PathDefault>(Constant::boolean(true)),
                                                std::move(result));
                }
                break;
            }

            default:
                break;
        }

        if (shouldGeneratePath(expr)) {
            if (tag == sbe::value::TypeTags::Array || tag == sbe::value::TypeTags::MinKey ||
                tag == sbe::value::TypeTags::MaxKey) {
                // The behavior of PathTraverse when it encounters an array is to apply its subpath
                // to every element of the array and not the array itself. When an expression is
                // comparing a field to an array, minKey or maxKey constant, we need to ensure that
                // these comparisons happen to every element of the array and the array itself.
                // For example:
                // find({a: [1]}) matches {a: [1]} and {a: [[1]]}
                // find({a: {$gt: MinKey()}}) matches {a: []}
                result = make<PathComposeA>(make<PathTraverse>(result, PathTraverse::kSingleLevel),
                                            result);
            } else {
                result = make<PathTraverse>(std::move(result), PathTraverse::kSingleLevel);
            }

            result = translateFieldRef(*(expr->fieldRef()), std::move(result));
        }

        _ctx.push(std::move(result));
    }

    template <class Composition, bool defaultResult>
    void visitAndOrExpression(const ListOfMatchExpression* expr) {
        const size_t childCount = expr->numChildren();
        if (childCount == 0) {
            generateBoolConstant(defaultResult);
            return;
        }
        if (childCount == 1) {
            return;
        }

        ABTVector nodes;
        for (size_t i = 0; i < childCount; i++) {
            nodes.push_back(_ctx.pop());
        }

        // Construct a balanced composition tree.
        maybeComposePaths<Composition>(nodes);
        _ctx.push(std::move(nodes.front()));
    }

    void unsupportedExpression(const MatchExpression* expr) const {
        uasserted(ErrorCodes::InternalErrorNotSupported,
                  str::stream() << "Match expression is not supported: " << expr->matchType());
    }

    /**
     * Returns whether the currently visiting expression should consider the path it's operating on
     * and build the appropriate ABT. This can return false for expressions within an $elemMatch
     * that operate against each value in an array (aka "elemMatch value").
     */
    bool shouldGeneratePath(const PathMatchExpression* expr) const {
        // The only case where any expression, including $elemMatch, should ignore it's path is if
        // it's directly under a value $elemMatch. The 'elemMatchStack' includes 'expr' if it's an
        // $elemMatch, so we need to look back an extra element.
        if (expr->matchType() == MatchExpression::MatchType::ELEM_MATCH_OBJECT ||
            expr->matchType() == MatchExpression::MatchType::ELEM_MATCH_VALUE) {
            return _ctx.shouldGeneratePathForElemMatch();
        }

        return _ctx.shouldGeneratePath();
    }

    // If we are parsing a partial index filter, we don't allow agg expressions.
    const bool _allowAggExpressions;

    // We don't own this
    ExpressionAlgebrizerContext& _ctx;
};

ABT generateMatchExpression(const MatchExpression* expr,
                            const bool allowAggExpressions,
                            const std::string& rootProjection,
                            const std::string& uniqueIdPrefix) {
    ExpressionAlgebrizerContext ctx(
        false /*assertExprSort*/, true /*assertPathSort*/, rootProjection, uniqueIdPrefix);
    ABTMatchExpressionPreVisitor preVisitor(ctx);
    ABTMatchExpressionVisitor postVisitor(ctx, allowAggExpressions);
    MatchExpressionWalker walker(&preVisitor, nullptr /*inVisitor*/, &postVisitor);
    tree_walker::walk<true, MatchExpression>(expr, &walker);
    return ctx.pop();
}

}  // namespace mongo::optimizer