summaryrefslogtreecommitdiff
path: root/src/mongo/db/query/projection_ast_path_tracking_visitor.h
blob: 8b33ff1af93482f85925432e0f745cc8800102b7 (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
/**
 *    Copyright (C) 2019-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.
 */

#pragma once

#include <list>
#include <stack>
#include <string>

#include "mongo/db/query/projection_ast.h"
#include "mongo/db/query/projection_ast_visitor.h"

namespace mongo {
namespace projection_ast {
using PathTrackingDummyDefaultType = void*;

/**
 * Class for storing context across calls to visit() in the PathTracking visitors.
 *
 * UserData is data that is made available to classes which inherit from the PathTracking visitors.
 */
template <class UserData = PathTrackingDummyDefaultType>
class PathTrackingVisitorContext {
public:
    PathTrackingVisitorContext() {}
    PathTrackingVisitorContext(UserData data) : _data{std::move(data)} {}

    auto fullPath() const {
        invariant(!_fieldNames.empty());
        invariant(!_fieldNames.top().empty());

        if (!_basePath) {
            return FieldPath(_fieldNames.top().front());
        }
        return FieldPath(
            FieldPath::getFullyQualifiedPath(_basePath->fullPath(), _fieldNames.top().front()));
    }

    const auto& basePath() const {
        return _basePath;
    }

    const std::string& childPath() const {
        return _fieldNames.top().front();
    }

    void setBasePath(boost::optional<FieldPath> path) {
        _basePath = std::move(path);
    }

    void popFrontFieldName() {
        _fieldNames.top().pop_front();
    }

    void popFieldNames() {
        invariant(_fieldNames.top().empty());
        _fieldNames.pop();
    }

    void pushFieldNames(std::list<std::string> fields) {
        _fieldNames.push(std::move(fields));
    }

    auto& data() {
        return _data;
    }

private:
    UserData _data;

    // Stores the field names to visit at each layer. Top of the stack is the most recently visited
    // layer.
    std::stack<std::list<std::string>> _fieldNames;

    // All but the last path component of the current path being visited. None if at the top-level
    // and there is no "parent" path.
    boost::optional<FieldPath> _basePath;
};

namespace {
/**
 * A path tracking pre-visitor used for maintaining field names while traversing the AST.
 *
 * This is intended to be used with the 'ProjectionPathTrackingWalker' only to correctly maintain
 * the state about the current path being visited.
 */
template <class UserData = PathTrackingDummyDefaultType, bool IsConst = true>
class PathTrackingPreVisitor final : public ProjectionASTVisitor<IsConst> {
public:
    PathTrackingPreVisitor(PathTrackingVisitorContext<UserData>* context) : _context{context} {
        invariant(_context);
    }

    void visit(tree_walker::MaybeConstPtr<IsConst, ProjectionPathASTNode> node) final {
        if (node->parent()) {
            _context->setBasePath(_context->fullPath());
            _context->popFrontFieldName();
        }

        _context->pushFieldNames({node->fieldNames().begin(), node->fieldNames().end()});
    }

    void visit(tree_walker::MaybeConstPtr<IsConst, MatchExpressionASTNode> node) final {}
    void visit(tree_walker::MaybeConstPtr<IsConst, ProjectionPositionalASTNode> node) final {}
    void visit(tree_walker::MaybeConstPtr<IsConst, ProjectionSliceASTNode> node) final {}
    void visit(tree_walker::MaybeConstPtr<IsConst, ProjectionElemMatchASTNode> node) final {}
    void visit(tree_walker::MaybeConstPtr<IsConst, ExpressionASTNode> node) final {}
    void visit(tree_walker::MaybeConstPtr<IsConst, BooleanConstantASTNode> node) final {}

private:
    PathTrackingVisitorContext<UserData>* _context;
};

/**
 * A path tracking post-visitor used for maintaining field names while traversing the AST.
 *
 * This is intended to be used with the 'PathTrackingWalker' only to correctly maintain the state
 * about the current path being visited.
 */
template <class UserData = PathTrackingDummyDefaultType, bool IsConst = true>
class PathTrackingPostVisitor final : public ProjectionASTVisitor<IsConst> {
public:
    PathTrackingPostVisitor(PathTrackingVisitorContext<UserData>* context) : _context{context} {
        invariant(_context);
    }

    void visit(tree_walker::MaybeConstPtr<IsConst, ProjectionPathASTNode> node) final {
        _context->popFieldNames();

        if (_context->basePath()) {
            // Update the context variable tracking the current path being traversed.
            const auto& fp = *_context->basePath();
            if (fp.getPathLength() == 1) {
                _context->setBasePath(boost::none);
            } else {
                // Pop the last path element.
                _context->setBasePath(FieldPath(fp.withoutLastElement()));
            }
        }
    }

    void visit(tree_walker::MaybeConstPtr<IsConst, ProjectionPositionalASTNode> node) final {
        _context->popFrontFieldName();
    }

    void visit(tree_walker::MaybeConstPtr<IsConst, ProjectionSliceASTNode> node) final {
        _context->popFrontFieldName();
    }

    void visit(tree_walker::MaybeConstPtr<IsConst, ProjectionElemMatchASTNode> node) final {
        _context->popFrontFieldName();
    }

    void visit(tree_walker::MaybeConstPtr<IsConst, ExpressionASTNode> node) final {
        _context->popFrontFieldName();
    }

    void visit(tree_walker::MaybeConstPtr<IsConst, BooleanConstantASTNode> node) final {
        _context->popFrontFieldName();
    }

    void visit(tree_walker::MaybeConstPtr<IsConst, MatchExpressionASTNode> node) final {}

private:
    PathTrackingVisitorContext<UserData>* _context;
};
}  // namespace

/**
 * A general path tracking walker to be used with projection AST visitors which need to track
 * the current projection path. Visitors will be able to access the current path via
 * 'PathTrackingVisitorContext', passed as 'context' parameter to the constructor of this class.
 * The walker and the visitors must be initialized with the same 'context' pointer.
 *
 * The visitors specified in the 'preVisitors' and 'postVisitors' parameters will be visited in
 * the same order as they were added to the vector.
 *
 * A note about the order the visitors are executed in: There are two special "path tracking"
 * visitors, which are responsible for maintaining state about which fields are being visited. The
 * path tracking pre-visitor is responsible for setting up the field name state for child nodes.
 * That is, when a ProjectionPathASTNode is encountered, the pre-visitor sets up the field name
 * state for the ProjectionPathASTNode's first child. After a leaf node has been visited, the
 * post-visitor is responsible for setting up the path state for its next sibling (if there is
 * one). This means that the order the path tracking visitors are executed in is significant: They
 * must both be run after the user-specified visitors.
 *
 */
template <class UserData = PathTrackingDummyDefaultType, bool IsConst = true>
class PathTrackingWalker final {
public:
    PathTrackingWalker(PathTrackingVisitorContext<UserData>* context,
                       std::vector<ProjectionASTVisitor<IsConst>*> preVisitors,
                       std::vector<ProjectionASTVisitor<IsConst>*> postVisitors)
        : _pathTrackingPreVisitor{context},
          _pathTrackingPostVisitor{context},
          _preVisitors{std::move(preVisitors)},
          _postVisitors{std::move(postVisitors)} {
        _preVisitors.push_back(&_pathTrackingPreVisitor);
        _postVisitors.push_back(&_pathTrackingPostVisitor);
    }

    void preVisit(tree_walker::MaybeConstPtr<IsConst, projection_ast::ASTNode> node) {
        for (auto visitor : _preVisitors) {
            node->acceptVisitor(visitor);
        }
    }

    void postVisit(tree_walker::MaybeConstPtr<IsConst, projection_ast::ASTNode> node) {
        for (auto visitor : _postVisitors) {
            node->acceptVisitor(visitor);
        }
    }

    void inVisit(long count, tree_walker::MaybeConstPtr<IsConst, ASTNode> node) {}

private:
    PathTrackingPreVisitor<UserData, IsConst> _pathTrackingPreVisitor;
    PathTrackingPostVisitor<UserData, IsConst> _pathTrackingPostVisitor;
    std::vector<ProjectionASTVisitor<IsConst>*> _preVisitors;
    std::vector<ProjectionASTVisitor<IsConst>*> _postVisitors;
};

template <class UserData>
using PathTrackingConstWalker = PathTrackingWalker<UserData, true>;

template <class UserData>
using PathTrackingMutableWalker = PathTrackingWalker<UserData, false>;

}  // namespace projection_ast
}  // namespace mongo