File: NormalizeRewritePath.cpp

package info (click to toggle)
swiftlang 6.1.3-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,791,644 kB
  • sloc: cpp: 9,901,738; ansic: 2,201,433; asm: 1,091,827; python: 308,252; objc: 82,166; f90: 80,126; lisp: 38,358; pascal: 25,559; sh: 20,429; ml: 5,058; perl: 4,745; makefile: 4,484; awk: 3,535; javascript: 3,018; xml: 918; fortran: 664; cs: 573; ruby: 396
file content (300 lines) | stat: -rw-r--r-- 8,995 bytes parent folder | download
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
//===--- NormalizeRewritePath.cpp - Canonical form of a rewrite path ------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Algorithm for reducing a rewrite path to left-canonical form:
//
// - Adjacent steps that are inverses of each other cancel out. for example
//   these two steps will be eliminated:
//
//     (A => B) ⊗ (B => A)
//
// - Interchange law moves rewrites "to the left", for example
//
//     X.(U => V) ⊗ (X => Y).V
//
//   becomes
//
//     (X => Y).U ⊗ Y.(U => V)
//
// These two transformations are iterated until fixed point to produce a
// equivalent rewrite path that is simpler.
//
// From "Homotopy reduction systems for monoid presentations",
// https://www.sciencedirect.com/science/article/pii/S0022404997000959
//
//===----------------------------------------------------------------------===//

#include "RewriteLoop.h"
#include "RewriteSystem.h"
#include "swift/Basic/Assertions.h"
#include "llvm/ADT/SmallVector.h"
#include <utility>

using namespace swift;
using namespace rewriting;

/// Returns true if this rewrite step is an inverse of \p other
/// (and vice versa).
bool RewriteStep::isInverseOf(const RewriteStep &other) const {
  if (Kind != other.Kind)
    return false;

  if (StartOffset != other.StartOffset)
    return false;

  if (Inverse != !other.Inverse)
    return false;

  switch (Kind) {
  case RewriteStep::Rule:
    return Arg == other.Arg;

  case RewriteStep::Relation:
    return Arg == other.Arg;

  default:
    return false;
  }

  ASSERT(EndOffset == other.EndOffset && "Bad whiskering?");
  return true;
}

bool RewriteStep::maybeSwapRewriteSteps(RewriteStep &other,
                                        const RewriteSystem &system) {
  if (Kind != other.Kind)
    return false;

  // Two rewrite steps are _orthogonal_ if they rewrite disjoint subterms
  // in context. Orthogonal rewrite steps commute, so we can canonicalize
  // a path by placing the left-most step first.
  //
  // Eg, A.U.B.(X => Y).C ⊗ A.(U => V).B.Y == A.(U => V).B.X ⊗ A.V.B.(X => Y).
  //
  // Or, in diagram form. We want to turn this:
  //
  //   ----- time ----->
  // +---------+---------+
  // |    A    |    A    |
  // +---------+---------+
  // |    U    | U ==> V |
  // +---------+---------+
  // |    B    |    B    |
  // +---------+---------+
  // | X ==> Y |    Y    |
  // +---------+---------+
  // |    C    |    C    |
  // +---------+---------+
  //
  // Into this:
  //
  // +---------+---------+
  // |    A    |    A    |
  // +---------+---------+
  // | U ==> V |    V    |
  // +---------+---------+
  // |    B    |    B    |
  // +---------+---------+
  // |    X    | X ==> Y |
  // +---------+---------+
  // |    C    |    C    |
  // +---------+---------+
  //
  // Note that
  //
  // StartOffset == |A|+|U|+|B|
  // EndOffset = |C|
  //
  // other.StartOffset = |A|
  // other.EndOffset = |B|+|Y|+|C|
  //
  // After interchange, we adjust:
  //
  // StartOffset = |A|
  // EndOffset = |B|+|X|+|C|
  //
  // other.StartOffset = |A|+|V|+|B|
  // other.EndOffset = |C|

  if (Kind == RewriteStep::Rule) {
    const auto &rule = system.getRule(Arg);
    auto lhs = (Inverse ? rule.getRHS() : rule.getLHS());
    auto rhs = (Inverse ? rule.getLHS() : rule.getRHS());

    const auto &otherRule = system.getRule(other.Arg);
    auto otherLHS = (other.Inverse ? otherRule.getRHS() : otherRule.getLHS());
    auto otherRHS = (other.Inverse ? otherRule.getLHS() : otherRule.getRHS());

    if (StartOffset < other.StartOffset + otherLHS.size())
      return false;

    std::swap(*this, other);
    EndOffset += (lhs.size() - rhs.size());
    other.StartOffset += (otherRHS.size() - otherLHS.size());

    return true;
  } else if (Kind == RewriteStep::Relation) {
    const auto &relation = system.getRelation(Arg);
    auto lhs = (Inverse ? relation.second : relation.first);
    auto rhs = (Inverse ? relation.first : relation.second);

    const auto &otherRelation = system.getRelation(other.Arg);
    auto otherLHS = (other.Inverse ? otherRelation.second : otherRelation.first);
    auto otherRHS = (other.Inverse ? otherRelation.first : otherRelation.second);

    if (StartOffset < other.StartOffset + otherLHS.size())
      return false;

    std::swap(*this, other);
    EndOffset += (lhs.size() - rhs.size());
    other.StartOffset += (otherRHS.size() - otherLHS.size());

    return true;
  }

  return false;
}

/// Cancels out adjacent rewrite steps that are inverses of each other.
/// This does not change either endpoint of the path, and the path does
/// not necessarily need to be a loop.
bool RewritePath::computeFreelyReducedForm() {
  unsigned j = 0;

  for (unsigned i = 0, e = Steps.size(); i < e; ++i) {
    // Pre-condition:
    // - Steps in the range [0, j-1] are freely reduced.
    // - Steps in the range [i, e-1] remain to be considered.
    if (j > 0) {
      // If Steps[j-1] and Steps[i] are inverses of each other,
      // discard both Steps[j-1] and Steps[i].
      const auto &otherStep = Steps[j - 1];
      const auto &step = Steps[i];

      if (otherStep.isInverseOf(step)) {
        --j;
        continue;
      }
    }

    // Post-condition:
    // - Steps in the range [0, j] are freely reduced.
    // - Steps in the range [i+1, e-1] remain to be considered.
    Steps[j] = Steps[i];
    ++j;
  }

  if (j == Steps.size())
    return false;

  Steps.erase(Steps.begin() + j, Steps.end());
  return true;
}

/// Apply the interchange rule until fixed point (see maybeSwapRewriteSteps()).
bool RewritePath::computeLeftCanonicalForm(const RewriteSystem &system) {
  bool changed = false;

  for (unsigned i = 1, e = Steps.size(); i < e; ++i) {
    // Pre-condition: steps in the range [0, i-1] are in left-canonical
    // normal form.
    //
    // If Steps[i] can be swapped with Steps[i-1], swap them, and check
    // if Steps[i-1] (the old Steps[i]) can be swapped with Steps[i-2],
    // etc.
    for (unsigned j = i; j >= 1; --j) {
      auto &prevStep = Steps[j - 1];
      auto &step = Steps[j];

      if (!prevStep.maybeSwapRewriteSteps(step, system))
        break;

      changed = true;
    }

    // Post-condition: steps in the range [0, i] are in left-canonical
    // normal form.
  }

  return changed;
}

/// Compute freely-reduced left-canonical normal form of a path.
bool RewritePath::computeNormalForm(const RewriteSystem &system) {
  // Note that computeFreelyReducedForm() and computeLeftCanonicalForm()
  // are both idempotent, but their composition is not.

  // Begin by freely reducing the path.
  bool changed = computeFreelyReducedForm();

  // Then, bring it into left canonical form.
  while (computeLeftCanonicalForm(system)) {
    changed = true;

    // If it was not already in left-canonical form, freely reduce it
    // again.
    if (!computeFreelyReducedForm()) {
      // If it was already freely reduced, then we're done, because it
      // is freely reduced *and* in left-canonical form.
      break;
    }

    // Otherwise, perform another round, since freely reducing may have
    // opened up new opportunities for left-canonicalization.
  }

  return changed;
}

/// Given a path that is a loop around the given basepoint, cancels out
/// pairs of terms from the ends that are inverses of each other, applying
/// the corresponding translation to the basepoint.
///
/// For example, consider this loop with basepoint 'X':
///
///   (X => Y.A) * (Y.A => Y.B) * Y.(B => A) * (Y.A => X)
///
/// The first step is the inverse of the last step, so the cyclic
/// reduction is the loop (Y.A => Y.B) * Y.(B => A), with a new
/// basepoint 'Y.A'.
bool RewritePath::computeCyclicallyReducedForm(MutableTerm &basepoint,
                                               const RewriteSystem &system) {
  RewritePathEvaluator evaluator(basepoint);
  unsigned count = 0;

  while (2 * count + 1 < size()) {
    auto left = Steps[count];
    auto right = Steps[Steps.size() - count - 1];
    if (!left.isInverseOf(right))
      break;

    // Update the basepoint by applying the first step in the path.
    evaluator.apply(left, system);

    ++count;
  }

  std::rotate(Steps.begin(), Steps.begin() + count, Steps.end() - count);
  Steps.erase(Steps.end() - 2 * count, Steps.end());

  basepoint = evaluator.getCurrentTerm();
  return count > 0;
}

/// Compute cyclically-reduced left-canonical normal form of a loop.
void RewriteLoop::computeNormalForm(const RewriteSystem &system) {
  bool changed = Path.computeNormalForm(system);
  changed |= Path.computeCyclicallyReducedForm(Basepoint, system);

  if (changed)
    markDirty();
}