aboutsummaryrefslogtreecommitdiffstats
path: root/yql/essentials/udfs/common/pire/pire_udf.cpp
blob: 0f9ffc5c21396f540028104c1a6b7c121ae6dc26 (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
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
#include <yql/essentials/public/udf/udf_value.h>
#include <yql/essentials/public/udf/udf_type_builder.h>
#include <yql/essentials/public/udf/udf_registrator.h>
#include <yql/essentials/public/udf/udf_value_builder.h>
#include <yql/essentials/public/udf/udf_terminator.h>

#include <library/cpp/regex/pire/regexp.h>
#include <library/cpp/regex/pire/pcre2pire.h>

#include <util/string/builder.h>

using namespace NRegExp;
using namespace NKikimr;
using namespace NUdf;

namespace {
    class TPireUdfBase: public TBoxedValue {
    protected:
        TPireUdfBase(TSourcePosition pos)
            : Pos_(pos)
        {}

        void SetCommonOptions(std::string_view& regex, TFsm::TOptions& options) {
            if (regex.size() >= 4U && regex.substr(0U, 4U) == "(?i)") {
                options.SetCaseInsensitive(true);
                regex.remove_prefix(4U);
            }
            if (UTF8Detect(regex) == UTF8) {
                options.SetCharset(CODES_UTF8);
            }
        }

        TSourcePosition Pos_;
    };

    class TPireMatch: public TPireUdfBase {
    public:
        class TFactory: public TPireUdfBase {
        public:
            TFactory(
                bool surroundMode,
                bool multiMode,
                TSourcePosition pos,
                size_t regexpsCount = 0)
                : TPireUdfBase(pos)
                , SurroundMode(surroundMode)
                , MultiMode(multiMode)
                , RegexpsCount(regexpsCount)
            {
            }

        private:
            TUnboxedValue Run(
                const IValueBuilder* valueBuilder,
                const TUnboxedValuePod* args) const final {
                return TUnboxedValuePod(
                    new TPireMatch(
                        valueBuilder,
                        args[0],
                        SurroundMode,
                        MultiMode,
                        Pos_,
                        RegexpsCount));
            }

            bool SurroundMode;
            bool MultiMode;
            size_t RegexpsCount;
        };

        static const TStringRef& Name(bool surroundMode, bool multiMode) {
            static auto match = TStringRef::Of("Match");
            static auto grep = TStringRef::Of("Grep");
            static auto multiMatch = TStringRef::Of("MultiMatch");
            static auto multiGrep = TStringRef::Of("MultiGrep");
            if (surroundMode) {
                return multiMode ? multiGrep : grep;
            } else {
                return multiMode ? multiMatch : match;
            }
        }

        TPireMatch(
            const IValueBuilder* valueBuilder,
            const TUnboxedValuePod& runConfig,
            bool surroundMode,
            bool multiMode,
            TSourcePosition pos,
            size_t regexpsCount)
            : TPireUdfBase(pos)
            , MultiMode(multiMode)
            , RegexpsCount(regexpsCount)
            , SurroundMode(surroundMode)
        {
            Y_UNUSED(valueBuilder);
            try {
                std::string_view regex(runConfig.AsStringRef());
                TFsm::TOptions options;
                options.SetSurround(surroundMode);
                SetCommonOptions(regex, options);
                if (multiMode) {
                    std::vector<std::string_view> parts;
                    StringSplitter(regex).Split('\n').AddTo(&parts);
                    for (const auto& part : parts) {
                        if (!part.empty()) {
                            if (Fsm_) try {
                                *Fsm_ = *Fsm_ | TFsm(TString(part), options);
                            } catch (const yexception&) {
                                UdfTerminate((TStringBuilder() << Pos_ << " Failed to glue up regexes, probably the finite state machine appeared to be too large").data());
                            } else {
                                Fsm_.Reset(new TFsm(TString(part), options));
                            }
                        }
                    }
                } else {
                    Fsm_.Reset(new TFsm(TString(regex), options));
                }
            } catch (const std::exception& e) {
                UdfTerminate((TStringBuilder() << Pos_ << " " << e.what()).data());
            }
        }

    private:
        TUnboxedValue Run(
            const IValueBuilder* valueBuilder,
            const TUnboxedValuePod* args) const final try {
            TUnboxedValue* items = nullptr;
            TUnboxedValue tuple;
            size_t i = 0;

            if (MultiMode) {
                tuple = valueBuilder->NewArray(RegexpsCount, items);

                for (i = 0; i < RegexpsCount; ++i) {
                    items[i] = TUnboxedValuePod(false);
                }
            }

            if (args[0]) {
                const auto input = args[0].AsStringRef();
                TMatcher matcher(*Fsm_);
                const bool isMatch = matcher.Match(input.Data(), input.Size(), SurroundMode, SurroundMode).Final();
                if (MultiMode) {
                    if (isMatch) {
                        const auto& matchedRegexps = matcher.MatchedRegexps();
                        size_t matchesCount = matchedRegexps.second - matchedRegexps.first;

                        for (i = 0; i < matchesCount; ++i) {
                            items[matchedRegexps.first[i]] = TUnboxedValuePod(true);
                        }
                    }
                    return tuple;

                } else {
                    return TUnboxedValuePod(isMatch);
                }

            } else {
                return MultiMode ? tuple : TUnboxedValue(TUnboxedValuePod(false));
            }
        } catch (const std::exception& e) {
            UdfTerminate((TStringBuilder() << Pos_ << " " << e.what()).data());
        }

    private:
        TUniquePtr<TFsm> Fsm_;
        bool MultiMode;
        size_t RegexpsCount;
        bool SurroundMode;
    };

    class TPireCapture: public TPireUdfBase {
    public:
        class TFactory: public TPireUdfBase {
        public:
            TFactory(TSourcePosition pos)
                : TPireUdfBase(pos)
            {}

        private:
            TUnboxedValue Run(const IValueBuilder*, const TUnboxedValuePod* args) const final try {
                return TUnboxedValuePod(new TPireCapture(args[0], Pos_));
            } catch (const std::exception& e) {
                UdfTerminate((TStringBuilder() << Pos_ << " " << e.what()).data());
            }
        };

        static const TStringRef& Name() {
            static auto name = TStringRef::Of("Capture");
            return name;
        }

        TPireCapture(const TUnboxedValuePod& runConfig, TSourcePosition pos)
            : TPireUdfBase(pos)
        {
            std::string_view regex(runConfig.AsStringRef());
            TFsm::TOptions options;
            SetCommonOptions(regex, options);
            Fsm_.Reset(new TSlowCapturingFsm(TString(regex), options));
        }

    private:
        TUnboxedValue Run(
            const IValueBuilder* valueBuilder,
            const TUnboxedValuePod* args) const final try {
            if (args[0]) {
                const std::string_view input = args[0].AsStringRef();

                TSlowSearcher searcher(*Fsm_);
                searcher.Search(input.data(), input.size());

                if (searcher.Captured()) {
                    const auto& captured = searcher.GetCaptured();
                    return valueBuilder->SubString(args[0], std::distance(input.begin(), captured.begin()), captured.length());
                }
            }

            return TUnboxedValue();
        } catch (const std::exception& e) {
            UdfTerminate((TStringBuilder() << Pos_ << " " << e.what()).data());
        }

        TUniquePtr<TSlowCapturingFsm> Fsm_;
    };

    class TPireReplace: public TPireUdfBase {
    public:
        class TFactory: public TPireUdfBase {
        public:
            TFactory(TSourcePosition pos)
                : TPireUdfBase(pos)
            {}

        private:
            TUnboxedValue Run(const IValueBuilder*, const TUnboxedValuePod* args) const final try {
                return TUnboxedValuePod(new TPireReplace(args[0], Pos_));
            } catch (const std::exception& e) {
                UdfTerminate((TStringBuilder() << Pos_ << " " << e.what()).data());
            }
        };

        static const TStringRef& Name() {
            static auto name = TStringRef::Of("Replace");
            return name;
        }

        TPireReplace(const TUnboxedValuePod& runConfig, TSourcePosition pos)
            : TPireUdfBase(pos)
        {
            std::string_view regex(runConfig.AsStringRef());
            TFsm::TOptions options;
            SetCommonOptions(regex, options);
            Fsm_.Reset(new TSlowCapturingFsm(TString(regex), options));
        }

    private:
        TUnboxedValue Run(
            const IValueBuilder* valueBuilder,
            const TUnboxedValuePod* args) const final try {
            if (args[0]) {
                const std::string_view input(args[0].AsStringRef());

                TSlowSearcher s(*Fsm_);
                s.Search(input.data(), input.size());
                if (s.Captured()) {
                    const auto& captured = s.GetCaptured();
                    const TString replacement(args[1].AsStringRef());
                    TString replaced(args[0].AsStringRef());
                    replaced.replace(std::distance(input.begin(), captured.begin()), captured.length(), replacement);
                    return valueBuilder->NewString(replaced);
                } else {
                    return TUnboxedValue(args[0]);
                }
            } else {
                return TUnboxedValue();
            }
        } catch (const std::exception& e) {
            UdfTerminate((TStringBuilder() << Pos_ << " " << e.what()).data());
        }

        TUniquePtr<TSlowCapturingFsm> Fsm_;
    };

    class TPireModule: public IUdfModule {
    public:
        TStringRef Name() const {
            return TStringRef::Of("Pire");
        }

        void CleanupOnTerminate() const final {
        }

        void GetAllFunctions(IFunctionsSink& sink) const final {
            sink.Add(TPireMatch::Name(true, true))->SetTypeAwareness();
            sink.Add(TPireMatch::Name(false, true))->SetTypeAwareness();
            sink.Add(TPireMatch::Name(true, false));
            sink.Add(TPireMatch::Name(false, false));
            sink.Add(TPireCapture::Name());
            sink.Add(TPireReplace::Name());
        }

        void BuildFunctionTypeInfo(
            const TStringRef& name,
            TType*,
            const TStringRef& typeConfig,
            ui32 flags,
            IFunctionTypeInfoBuilder& builder) const final try {
            const bool typesOnly = (flags & TFlags::TypesOnly);
            const bool isMatch = (TPireMatch::Name(false, false) == name);
            const bool isGrep = (TPireMatch::Name(true, false) == name);
            const bool isMultiMatch = (TPireMatch::Name(false, true) == name);
            const bool isMultiGrep = (TPireMatch::Name(true, true) == name);

            if (isMatch || isGrep) {
                builder.SimpleSignature<bool(TOptional<char*>)>()
                    .RunConfig<const char*>();

                if (!typesOnly) {
                    builder.Implementation(new TPireMatch::TFactory(isGrep, false, builder.GetSourcePosition()));
                }
            } else if (isMultiMatch || isMultiGrep) {
                const auto boolType = builder.SimpleType<bool>();
                const auto optionalStringType = builder.Optional()->Item<char*>().Build();
                const std::string_view regexp(typeConfig);
                const size_t regexpCount = std::count(regexp.begin(), regexp.end(), '\n') + 1;
                const auto tuple = builder.Tuple();
                for (size_t i = 0; i < regexpCount; ++i) {
                    tuple->Add(boolType);
                }
                const auto tupleType = tuple->Build();
                builder.Args(1)->Add(optionalStringType).Done().Returns(tupleType).RunConfig<char*>();

                if (!typesOnly) {
                    builder.Implementation(new TPireMatch::TFactory(isMultiGrep, true, builder.GetSourcePosition(), regexpCount));
                }
            } else if (TPireCapture::Name() == name) {
                builder.SimpleSignature<TOptional<char*>(TOptional<char*>)>()
                    .RunConfig<char*>();

                if (!typesOnly) {
                    builder.Implementation(new TPireCapture::TFactory(builder.GetSourcePosition()));
                }
            } else if (TPireReplace::Name() == name) {
                builder.SimpleSignature<TOptional<char*>(TOptional<char*>, char*)>()
                    .RunConfig<char*>();

                if (!typesOnly) {
                    builder.Implementation(new TPireReplace::TFactory(builder.GetSourcePosition()));
                }
            }
        } catch (const std::exception& e) {
            builder.SetError(CurrentExceptionMessage());
        }
    };

}

REGISTER_MODULES(TPireModule)