summaryrefslogtreecommitdiffstats
path: root/yql/essentials/sql/v1/format/check/ast.cpp
blob: a8163a2b52b6d4580ee57339d22943d88fb58fde (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
#include "ast.h"

#include <util/generic/stack.h>

#include <utility>

namespace NSQLFormat {

namespace {

bool IsUnstable(const NYql::TAstNode* x) {
    return x->IsAtom() && (x->GetFlags() & NYql::TAstNodeFlags::UnstableFormat) != 0;
}

} // namespace

TMaybe<bool> AreAstEqual(const NYql::TAstNode* lhs, const NYql::TAstNode* rhs) {
    bool isUnstable = false;

    TStack<std::pair<const NYql::TAstNode*, const NYql::TAstNode*>> stack;
    stack.emplace(lhs, rhs);

    while (!stack.empty()) {
        const auto [lhs, rhs] = std::move(stack.top());
        stack.pop();

        if (IsUnstable(lhs) && IsUnstable(rhs)) {
            isUnstable = true;
            continue;
        }

        if (lhs->GetType() != rhs->GetType()) {
            return false;
        }

        switch (lhs->GetType()) {
            case NYql::TAstNode::EType::Atom: {
                if (lhs->GetFlags() != rhs->GetFlags()) {
                    return false;
                }

                if (lhs->GetContent() != rhs->GetContent()) {
                    return false;
                }

                break;
            }
            case NYql::TAstNode::EType::List: {
                if (lhs->GetChildrenCount() != rhs->GetChildrenCount()) {
                    return false;
                }

                for (size_t i = 0; i < lhs->GetChildrenCount(); ++i) {
                    stack.emplace(lhs->GetChild(i), rhs->GetChild(i));
                }

                break;
            }
        }
    }

    if (isUnstable) {
        return Nothing();
    }

    return true;
}

} // namespace NSQLFormat