aboutsummaryrefslogtreecommitdiffstats
path: root/yql/essentials/core/cbo/cbo_hints.cpp
blob: 630bb3e6b03a067a8bfd85be6575438af9af08d0 (plain) (blame)
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
#include "cbo_optimizer_new.h"

#include <util/string/join.h>
#include <util/string/printf.h>
#include <library/cpp/iterator/zip.h>

using namespace NYql;

class TOptimizerHintsParser {
public:
    TOptimizerHintsParser(const TString& text) 
        : Pos(-1)
        , Size(static_cast<i32>(text.size()) - 1)
        , Text(text)
    {}

    TOptimizerHints Parse() {
        Start();
        return Hints;
    }

private:
    void Start() {
        while (Pos < Size) {
            auto hintType = Keyword({"JoinOrder", "Leading", "JoinType", "Rows"});
            if (hintType == "JoinOrder" || hintType == "Leading") {
                JoinOrder(hintType == "Leading");
            } else if (hintType == "JoinType") {
                JoinType();
            } else if (hintType == "Rows"){
                Rows();
            } else {
                ParseError(Sprintf("Undefined hints type: %s", hintType.c_str()), Pos - hintType.size());
            }

            SkipWhiteSpaces();
        }
    }

    TVector<TString> CollectLabels() {
        TVector<TString> labels;
        while (auto maybeTerm = MaybeLabel()) {
            labels.push_back(maybeTerm.value());
        }
        return labels;
    }

    void JoinType() {        
        i32 beginPos = Pos + 1;
        
        Keyword({"("});

        i32 labelsBeginPos = Pos + 1;
        TVector<TString> labels = CollectLabels();
        if (labels.size() <= 1) {
            ParseError(Sprintf("Bad labels for JoinType hint: %s, example of the format: JoinType(t1 t2 Shuffle)", JoinSeq(", ", labels).c_str()), labelsBeginPos);
        }
        TString reqJoinAlgoStr = std::move(labels.back());
        labels.pop_back();

        Keyword({")"});
        
        TVector<EJoinAlgoType> joinAlgos = {EJoinAlgoType::GraceJoin, EJoinAlgoType::LookupJoin, EJoinAlgoType::MapJoin};
        TVector<TString> joinAlgosStr = {"Shuffle", "Lookup", "Broadcast"};

        for (const auto& [JoinType, joinAlgoStr]: Zip(joinAlgos, joinAlgosStr)) {
            if (reqJoinAlgoStr == joinAlgoStr) {
                Hints.JoinAlgoHints->PushBack(std::move(labels), JoinType, "JoinType" + Text.substr(beginPos, Pos - beginPos + 1));
                return;
            }
        }
       
        ParseError(Sprintf("Unknown JoinType: '%s', supported algos: [%s]", reqJoinAlgoStr.c_str(), JoinSeq(", ", joinAlgosStr).c_str()), Pos - reqJoinAlgoStr.size());
        Y_UNREACHABLE();
    }

    void JoinOrder(bool leading /* is keyword "Leading" or "JoinOrder" */) {
        i32 beginPos = Pos + 1;

        Keyword({"("});
        auto joinOrderHintTree = JoinOrderLabels();
        Keyword({")"});

        Hints.JoinOrderHints->PushBack(
            std::move(joinOrderHintTree), 
            leading? "Leading" : "JoinOrder" + Text.substr(beginPos, Pos - beginPos + 1)
        );
    }

    std::shared_ptr<TJoinOrderHints::ITreeNode> JoinOrderLabels() {
        auto lhs = JoinOrderLabel();
        auto rhs = JoinOrderLabel();
        return std::make_shared<TJoinOrderHints::TJoinNode>(std::move(lhs), std::move(rhs));
    }

    std::shared_ptr<TJoinOrderHints::ITreeNode> JoinOrderLabel() {
        if (auto maybeLabel = MaybeLabel()) {
            return std::make_shared<TJoinOrderHints::TRelationNode>(std::move(maybeLabel.value()));
        } else if (auto maybeBracket = MaybeKeyword({"("})) {
            auto join = JoinOrderLabels();
            Keyword({")"});
            return join;
        } 

        ParseError(Sprintf("JoinOrder args must be either a relation, either a join, example of the format: JoinOrder(t1 (t2 t3))"), Pos);
        Y_UNREACHABLE();
    }

    void Rows() {
        i32 beginPos = Pos + 1;

        Keyword({"("});

        TVector<TString> labels = CollectLabels();
        auto signStr = Keyword({"+", "-", "/", "*", "#"});
        char sign = signStr[0];
        auto value = Number();
        Keyword({")"});
        
        TCardinalityHints::ECardOperation op;
        switch (sign) {
            case '+': { op = TCardinalityHints::ECardOperation::Add; break; }
            case '-': { op = TCardinalityHints::ECardOperation::Subtract; break; }
            case '/': { op = TCardinalityHints::ECardOperation::Divide; break; }
            case '*': { op = TCardinalityHints::ECardOperation::Multiply; break; }
            case '#': { op = TCardinalityHints::ECardOperation::Replace; break; }
            default: {ParseError(Sprintf("Unknown operation: '%c'", sign), Pos - 1); Y_UNREACHABLE();}
        }

        Hints.CardinalityHints->PushBack(std::move(labels), op, value, "Rows" + Text.substr(beginPos, Pos - beginPos + 1));
    }

private:
    // Expressions
    void ParseError(const TString& err, i32 pos) {
        auto [line, linePos] = GetLineAndLinePosFromTextPos(pos);
        Y_ENSURE(false, Sprintf("Optimizer hints parser error at [line:%d, pos:%d], msg: %s", line, linePos, err.c_str()));
    }

    TString Label() {
        return Term(Letters() | Digits());
    }

    std::optional<TString> MaybeLabel() {
        try {
            return Label();
        } catch (...) {
            return std::nullopt;
        }
    }

    TString Term(const std::bitset<256>& allowedSym = {}) {
        SkipWhiteSpaces();
        Y_ENSURE(Pos < Size, "Expected <string>, but got end of the string.");

        TString term;
        while (Pos < Size) {
            try {
                term.push_back(Char(allowedSym));
            } catch (...) {
                break;
            }
        }

        if (term.empty()) {
            ParseError("Expected a term!", Pos);
        }
        return term;
    }

    char Char(unsigned char c) {
        std::bitset<256> allowed;
        allowed[c] = 1; 
        return Char(allowed);
    }

    char Char(unsigned char intervalBegin, unsigned char intervalEnd) {
        std::bitset<256> allowed;
        for (size_t i = intervalBegin; i <= intervalEnd; ++i) {
            allowed[i] = 1;
        }
        return Char(allowed);
    }
 
    char Char(const std::bitset<256>& allowedSymbols = {}) {
        Y_ENSURE(Pos < Size, Sprintf("Expected [%s], but got end of the string.", ""));

        char nextSym = Text[Pos + 1];
        if (allowedSymbols.count() == 0) {
            ++Pos;
            return nextSym;
        }

        for (size_t i = 0; i < allowedSymbols.size(); ++i) {
            if (allowedSymbols[i] && tolower(i) == tolower(nextSym)) {
                ++Pos;
                return nextSym;
            }
        }

        ParseError(Sprintf("Expected [%s], but got [%c]", "", nextSym), Pos);
        Y_UNREACHABLE();
    }

    std::optional<TString> MaybeKeyword(const TVector<TString>& keywords) {
        try {
            return Keyword(keywords);
        } catch(...) {
            return std::nullopt;
        }
    }

    TString Keyword(const TVector<TString>& keywords) {
        SkipWhiteSpaces();
        Y_ENSURE(Pos < Size, Sprintf("Expected [%s], but got end of the string.", JoinSeq(", ", keywords).c_str()));

        for (const auto& keyword: keywords) {
            size_t lowInclude = Pos + 1;
            size_t highExclude = lowInclude + keyword.size();

            if (Text.substr(lowInclude, highExclude - lowInclude).equal(keyword)) {
                Pos += keyword.size();
                return keyword;
            }
        }

        ParseError(Sprintf("Expected [%s], but got [%c]", JoinSeq(", ", keywords).c_str(), Text[Pos + 1]), Pos);
        Y_UNREACHABLE();
    }

    double Number() {
        SkipWhiteSpaces();
        Y_ENSURE(Pos < Size, Sprintf("Expected number, but got end of the string."));

        TString number;
        if (auto maybeSign = MaybeKeyword({"+", "-"})) {
            number.push_back(maybeSign.value()[0]);
        }

        auto term = Term(Digits() | Chars(".-e")); // for double like 1.0 / 1e9
        try {
            return std::stod(term);
        } catch (...) {
            ParseError(Sprintf("Expected a number, got [%s]", term.c_str()), Pos - term.size());
        }
        Y_UNREACHABLE();
    }

private:
    // Helpers
    constexpr std::bitset<256> Chars(const TString& s) {
        std::bitset<256> res;

        for (char c: s) {
            res[c] = 1;
        }

        return res;
    }

    constexpr std::bitset<256> Letters() {
        std::bitset<256> res;

        for (unsigned char i = 'a'; i <= 'z'; ++i) {
            res[i] = 1;
        }
        for (unsigned char i = 'A'; i <= 'Z'; ++i) {
            res[i] = 1;
        }

        return res;
    }

    constexpr std::bitset<256> Digits() {
        std::bitset<256> res;

        for (unsigned char i = '0'; i <= '9'; ++i) {
            res[i] = 1;
        }

        return res;
    }

    void SkipWhiteSpaces() {
        for (; Pos < Size && isspace(Text[Pos + 1]); ++Pos) {
        }
    }

    std::pair<i32, i32> GetLineAndLinePosFromTextPos(i32 pos) {
        i32 Line = 0;
        i32 LinePos = 0;

        for (i32 i = 0; i <= pos && i < static_cast<i32>(Text.size()); ++i) {
            if (Text[i] == '\n') {
                LinePos = 0;
                ++Line;
            } else {
                ++LinePos;
            }
        }

        return {Line, LinePos};
    }

private:
    i32 Pos;
    const i32 Size;
    const TString& Text;

private:
    TOptimizerHints Hints;
};

TOptimizerHints TOptimizerHints::Parse(const TString& text) {
    return TOptimizerHintsParser(text).Parse();
}