File: lcs.h

package info (click to toggle)
spirv-tools 2025.1~rc1-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 27,036 kB
  • sloc: cpp: 437,999; javascript: 5,893; python: 2,965; ansic: 466; sh: 415; ruby: 88; makefile: 18; lisp: 9
file content (224 lines) | stat: -rw-r--r-- 7,492 bytes parent folder | download | duplicates (22)
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
// Copyright (c) 2022 Google LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef SOURCE_DIFF_LCS_H_
#define SOURCE_DIFF_LCS_H_

#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <stack>
#include <vector>

namespace spvtools {
namespace diff {

// The result of a diff.
using DiffMatch = std::vector<bool>;

// Helper class to find the longest common subsequence between two function
// bodies.
template <typename Sequence>
class LongestCommonSubsequence {
 public:
  LongestCommonSubsequence(const Sequence& src, const Sequence& dst)
      : src_(src),
        dst_(dst),
        table_(src.size(), std::vector<DiffMatchEntry>(dst.size())) {}

  // Given two sequences, it creates a matching between them.  The elements are
  // simply marked as matched in src and dst, with any unmatched element in src
  // implying a removal and any unmatched element in dst implying an addition.
  //
  // Returns the length of the longest common subsequence.
  template <typename T>
  uint32_t Get(std::function<bool(T src_elem, T dst_elem)> match,
               DiffMatch* src_match_result, DiffMatch* dst_match_result);

 private:
  struct DiffMatchIndex {
    uint32_t src_offset;
    uint32_t dst_offset;
  };

  template <typename T>
  void CalculateLCS(std::function<bool(T src_elem, T dst_elem)> match);
  void RetrieveMatch(DiffMatch* src_match_result, DiffMatch* dst_match_result);
  bool IsInBound(DiffMatchIndex index) {
    return index.src_offset < src_.size() && index.dst_offset < dst_.size();
  }
  bool IsCalculated(DiffMatchIndex index) {
    assert(IsInBound(index));
    return table_[index.src_offset][index.dst_offset].valid;
  }
  bool IsCalculatedOrOutOfBound(DiffMatchIndex index) {
    return !IsInBound(index) || IsCalculated(index);
  }
  uint32_t GetMemoizedLength(DiffMatchIndex index) {
    if (!IsInBound(index)) {
      return 0;
    }
    assert(IsCalculated(index));
    return table_[index.src_offset][index.dst_offset].best_match_length;
  }
  bool IsMatched(DiffMatchIndex index) {
    assert(IsCalculated(index));
    return table_[index.src_offset][index.dst_offset].matched;
  }
  void MarkMatched(DiffMatchIndex index, uint32_t best_match_length,
                   bool matched) {
    assert(IsInBound(index));
    DiffMatchEntry& entry = table_[index.src_offset][index.dst_offset];
    assert(!entry.valid);

    entry.best_match_length = best_match_length & 0x3FFFFFFF;
    assert(entry.best_match_length == best_match_length);
    entry.matched = matched;
    entry.valid = true;
  }

  const Sequence& src_;
  const Sequence& dst_;

  struct DiffMatchEntry {
    DiffMatchEntry() : best_match_length(0), matched(false), valid(false) {}

    uint32_t best_match_length : 30;
    // Whether src[i] and dst[j] matched.  This is an optimization to avoid
    // calling the `match` function again when walking the LCS table.
    uint32_t matched : 1;
    // Use for the recursive algorithm to know if the contents of this entry are
    // valid.
    uint32_t valid : 1;
  };

  std::vector<std::vector<DiffMatchEntry>> table_;
};

template <typename Sequence>
template <typename T>
uint32_t LongestCommonSubsequence<Sequence>::Get(
    std::function<bool(T src_elem, T dst_elem)> match,
    DiffMatch* src_match_result, DiffMatch* dst_match_result) {
  CalculateLCS(match);
  RetrieveMatch(src_match_result, dst_match_result);
  return GetMemoizedLength({0, 0});
}

template <typename Sequence>
template <typename T>
void LongestCommonSubsequence<Sequence>::CalculateLCS(
    std::function<bool(T src_elem, T dst_elem)> match) {
  // The LCS algorithm is simple.  Given sequences s and d, with a:b depicting a
  // range in python syntax:
  //
  //     lcs(s[i:], d[j:]) =
  //         lcs(s[i+1:], d[j+1:]) + 1                        if s[i] == d[j]
  //         max(lcs(s[i+1:], d[j:]), lcs(s[i:], d[j+1:]))               o.w.
  //
  // Once the LCS table is filled according to the above, it can be walked and
  // the best match retrieved.
  //
  // This is a recursive function with memoization, which avoids filling table
  // entries where unnecessary.  This makes the best case O(N) instead of
  // O(N^2).  The implemention uses a std::stack to avoid stack overflow on long
  // sequences.

  if (src_.empty() || dst_.empty()) {
    return;
  }

  std::stack<DiffMatchIndex> to_calculate;
  to_calculate.push({0, 0});

  while (!to_calculate.empty()) {
    DiffMatchIndex current = to_calculate.top();
    to_calculate.pop();
    assert(IsInBound(current));

    // If already calculated through another path, ignore it.
    if (IsCalculated(current)) {
      continue;
    }

    if (match(src_[current.src_offset], dst_[current.dst_offset])) {
      // If the current elements match, advance both indices and calculate the
      // LCS if not already.  Visit `current` again afterwards, so its
      // corresponding entry will be updated.
      DiffMatchIndex next = {current.src_offset + 1, current.dst_offset + 1};
      if (IsCalculatedOrOutOfBound(next)) {
        MarkMatched(current, GetMemoizedLength(next) + 1, true);
      } else {
        to_calculate.push(current);
        to_calculate.push(next);
      }
      continue;
    }

    // We've reached a pair of elements that don't match.  Calculate the LCS for
    // both cases of either being left unmatched and take the max.  Visit
    // `current` again afterwards, so its corresponding entry will be updated.
    DiffMatchIndex next_src = {current.src_offset + 1, current.dst_offset};
    DiffMatchIndex next_dst = {current.src_offset, current.dst_offset + 1};

    if (IsCalculatedOrOutOfBound(next_src) &&
        IsCalculatedOrOutOfBound(next_dst)) {
      uint32_t best_match_length =
          std::max(GetMemoizedLength(next_src), GetMemoizedLength(next_dst));
      MarkMatched(current, best_match_length, false);
      continue;
    }

    to_calculate.push(current);
    if (!IsCalculatedOrOutOfBound(next_src)) {
      to_calculate.push(next_src);
    }
    if (!IsCalculatedOrOutOfBound(next_dst)) {
      to_calculate.push(next_dst);
    }
  }
}

template <typename Sequence>
void LongestCommonSubsequence<Sequence>::RetrieveMatch(
    DiffMatch* src_match_result, DiffMatch* dst_match_result) {
  src_match_result->clear();
  dst_match_result->clear();

  src_match_result->resize(src_.size(), false);
  dst_match_result->resize(dst_.size(), false);

  DiffMatchIndex current = {0, 0};
  while (IsInBound(current)) {
    if (IsMatched(current)) {
      (*src_match_result)[current.src_offset++] = true;
      (*dst_match_result)[current.dst_offset++] = true;
      continue;
    }

    if (GetMemoizedLength({current.src_offset + 1, current.dst_offset}) >=
        GetMemoizedLength({current.src_offset, current.dst_offset + 1})) {
      ++current.src_offset;
    } else {
      ++current.dst_offset;
    }
  }
}

}  // namespace diff
}  // namespace spvtools

#endif  // SOURCE_DIFF_LCS_H_