aboutsummaryrefslogtreecommitdiffstats
path: root/yql/essentials/providers/common/transform/yql_visit.h
blob: 438e6d76bacceb393646c328d92f61c652747674 (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
#pragma once

#include <yql/essentials/core/yql_graph_transformer.h>
#include <yql/essentials/core/expr_nodes/yql_expr_nodes.h>
#include <yql/essentials/ast/yql_expr.h>

#include <util/generic/hash.h>
#include <util/generic/strbuf.h>

#include <functional>
#include <initializer_list>

namespace NYql {

class TVisitorTransformerBase: public TSyncTransformerBase {
public:
    using THandler = std::function<TStatus(const TExprNode::TPtr&, TExprNode::TPtr&, TExprContext&)>;

    TVisitorTransformerBase(bool failOnUnknown)
        : FailOnUnknown(failOnUnknown)
    {
    }

    TStatus DoTransform(TExprNode::TPtr input, TExprNode::TPtr& output, TExprContext& ctx) final;

    void Rewind() final {
    }

    bool CanParse(const TExprNode& node) const {
        return Handlers.contains(node.Content());
    }

protected:
    void AddHandler(std::initializer_list<TStringBuf> names, THandler handler);

    template <class TDerived>
    THandler Hndl(TStatus(TDerived::* handler)(const TExprNode::TPtr&, TExprNode::TPtr&, TExprContext&)) {
        return [this, handler] (TExprNode::TPtr input, TExprNode::TPtr& output, TExprContext& ctx) {
            return (static_cast<TDerived*>(this)->*handler)(input, output, ctx);
        };
    }

    template <class TDerived>
    THandler Hndl(TStatus(TDerived::* handler)(const TExprNode::TPtr&, TExprContext&)) {
        return [this, handler] (TExprNode::TPtr input, TExprNode::TPtr& /*output*/, TExprContext& ctx) {
            return (static_cast<TDerived*>(this)->*handler)(input, ctx);
        };
    }

    template <class TDerived>
    THandler Hndl(TStatus(TDerived::* handler)(NNodes::TExprBase, TExprContext&)) {
        return [this, handler] (TExprNode::TPtr input, TExprNode::TPtr& /*output*/, TExprContext& ctx) {
            return (static_cast<TDerived*>(this)->*handler)(NNodes::TExprBase(input), ctx);
        };
    }

    THandler Hndl(TStatus(*handler)(const TExprNode::TPtr&, TExprContext&)) {
        return [handler] (TExprNode::TPtr input, TExprNode::TPtr& /*output*/, TExprContext& ctx) {
            return handler(input, ctx);
        };
    }

    THandler Hndl(TStatus(*handler)(NNodes::TExprBase, TExprContext&)) {
        return [handler] (TExprNode::TPtr input, TExprNode::TPtr& /*output*/, TExprContext& ctx) {
            return handler(NNodes::TExprBase(input), ctx);
        };
    }

protected:
    const bool FailOnUnknown;
    THashMap<TStringBuf, THandler> Handlers;
};

} // NYql