File: RequirementBuilder.cpp

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (379 lines) | stat: -rw-r--r-- 12,921 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
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
//===--- RequirementBuilder.cpp - Building requirements from rules --------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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
//
//===----------------------------------------------------------------------===//
//
// This file implements the final step in generic signature minimization,
// building requirements from a set of minimal, canonical rewrite rules.
//
// The main entry point is RequirementMachine::buildRequirementsFromRules(),
// called from the RequirementSignatureRequest, AbstractGenericSignatureRequest
// and InferredGenericSignatureRequest requests defined in
// RequirementMachineRequests.cpp.
//
//===----------------------------------------------------------------------===//

#include "RequirementMachine.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Requirement.h"
#include "swift/AST/RequirementSignature.h"
#include "swift/AST/Types.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallVector.h"
#include <vector>

using namespace swift;
using namespace rewriting;

namespace {

/// Represents a set of types related by same-type requirements, and an
/// optional concrete type requirement.
struct ConnectedComponent {
  llvm::SmallVector<Type, 2> Members;
  llvm::SmallVector<Identifier, 1> Aliases;
  Type ConcreteType;

  void buildRequirements(Type subjectType,
                         RequirementKind kind,
                         std::vector<Requirement> &reqs,
                         std::vector<ProtocolTypeAlias> &aliases);
};

/// Case 1: A set of rewrite rules of the form:
///
///   B => A
///   C => A
///   D => A
///
/// Become a series of same-type requirements
///
///   A == B, B == C, C == D
///
/// Case 2: A set of rewrite rules of the form:
///
///   A.[concrete: X] => A
///   B => A
///   C => A
///   D => A
///
/// Become a series of same-type requirements
///
///   A == X, B == X, C == X, D == X
void ConnectedComponent::buildRequirements(Type subjectType,
                                           RequirementKind kind,
                                           std::vector<Requirement> &reqs,
                                           std::vector<ProtocolTypeAlias> &aliases) {
  std::sort(Members.begin(), Members.end(),
            [](Type first, Type second) -> bool {
              return compareDependentTypes(first, second) < 0;
            });

  if (!ConcreteType) {
    for (auto name : Aliases) {
      aliases.emplace_back(name, subjectType);
    }

    for (auto constraintType : Members) {
      reqs.emplace_back(kind, subjectType, constraintType);
      subjectType = constraintType;
    }

  } else {
    // Shape requirements cannot be concrete.
    assert(kind == RequirementKind::SameType);

    // If there are multiple protocol typealiases in the connected component,
    // lower them all to a series of identical concrete-type aliases.
    for (auto name : Aliases) {
      aliases.emplace_back(name, ConcreteType);
    }

    // If the most canonical representative in the connected component is an
    // unresolved DependentMemberType, it must be of the form 'Self.A'
    // where 'A' is an alias. Emit the concrete-type alias itself.
    if (auto *memberTy = subjectType->getAs<DependentMemberType>()) {
      if (memberTy->getAssocType() == nullptr) {
        auto *paramTy = memberTy->getBase()->castTo<GenericTypeParamType>();
        assert(paramTy->getDepth() == 0 && paramTy->getIndex() == 0);
        (void) paramTy;

        aliases.emplace_back(memberTy->getName(), ConcreteType);

        assert(Members.empty());
        return;
      }
    }

    // Otherwise, the most canonical representative must be a resolved
    // associated type. Emit a requirement.
    reqs.emplace_back(RequirementKind::SameType,
                      subjectType, ConcreteType);

    // Finally, emit a concrete type requirement for all resolved type members
    // of the connected component.
    for (auto constraintType : Members) {
      reqs.emplace_back(RequirementKind::SameType,
                        constraintType, ConcreteType);
    }
  }
}

/// Once we're done with minimization, we turn the minimal rules into requirements.
/// This is in a sense the inverse of RuleBuilder in RequirementLowering.cpp.
class RequirementBuilder {
  // Input parameters.
  const RewriteSystem &System;
  const PropertyMap &Map;
  ArrayRef<GenericTypeParamType *> GenericParams;
  bool ReconstituteSugar;
  bool Debug;

  // Temporary state populated by addRequirementRules() and
  // addTypeAliasRules().
  llvm::SmallDenseMap<Term, ConnectedComponent> Components;

public:
  // Results.
  std::vector<Requirement> Reqs;
  std::vector<ProtocolTypeAlias> Aliases;

  RequirementBuilder(const RewriteSystem &system, const PropertyMap &map,
                     ArrayRef<GenericTypeParamType *> genericParams,
                     bool reconstituteSugar)
    : System(system), Map(map),
      GenericParams(genericParams),
      ReconstituteSugar(reconstituteSugar),
      Debug(System.getDebugOptions().contains(DebugFlags::Minimization)) {}

  void addRequirementRules(ArrayRef<unsigned> rules);
  void addTypeAliasRules(ArrayRef<unsigned> rules);

  void processConnectedComponents();

  void sortRequirements();
  void sortTypeAliases();
};

}  // end namespace

static Type replaceTypeParametersWithErrorTypes(Type type) {
  return type.transformRec([](Type t) -> std::optional<Type> {
    if (t->isTypeParameter())
      return ErrorType::get(t->getASTContext());
    return std::nullopt;
  });
}

void RequirementBuilder::addRequirementRules(ArrayRef<unsigned> rules) {
  // Convert a rewrite rule into a requirement.
  auto createRequirementFromRule = [&](const Rule &rule) {
    if (auto prop = rule.isPropertyRule()) {
      auto subjectType = Map.getTypeForTerm(rule.getRHS(), GenericParams);

      switch (prop->getKind()) {
      case Symbol::Kind::Protocol:
        Reqs.emplace_back(RequirementKind::Conformance,
                          subjectType,
                          prop->getProtocol()->getDeclaredInterfaceType());
        return;

      case Symbol::Kind::Layout:
        Reqs.emplace_back(RequirementKind::Layout,
                          subjectType,
                          prop->getLayoutConstraint());
        return;

      case Symbol::Kind::Superclass:
      case Symbol::Kind::ConcreteType: {
        bool containsUnresolvedSymbols = false;
        for (auto term : prop->getSubstitutions()) {
          containsUnresolvedSymbols |= term.containsUnresolvedSymbols();
        }

        Type concreteType = Map.getTypeFromSubstitutionSchema(
                                prop->getConcreteType(),
                                prop->getSubstitutions(),
                                GenericParams, MutableTerm());
        if (containsUnresolvedSymbols || rule.isRecursive())
          concreteType = replaceTypeParametersWithErrorTypes(concreteType);

        if (ReconstituteSugar)
          concreteType = concreteType->reconstituteSugar(/*recursive=*/true);

        if (prop->getKind() == Symbol::Kind::Superclass) {
          Reqs.emplace_back(RequirementKind::Superclass,
                            subjectType, concreteType);
        } else {
          auto &component = Components[rule.getRHS()];
          assert(!component.ConcreteType);
          component.ConcreteType = concreteType;
        }
        return;
      }

      case Symbol::Kind::ConcreteConformance:
        // "Concrete conformance requirements" are not recorded in the generic
        // signature.
        return;

      case Symbol::Kind::Name:
      case Symbol::Kind::AssociatedType:
      case Symbol::Kind::GenericParam:
      case Symbol::Kind::Shape:
        break;
      }

      llvm_unreachable("Invalid symbol kind");
    }

    assert(rule.getLHS().back().getKind() != Symbol::Kind::Protocol);

    MutableTerm constraintTerm(rule.getLHS());
    if (constraintTerm.back().getKind() == Symbol::Kind::Shape) {
      assert(rule.getRHS().back().getKind() == Symbol::Kind::Shape);
      // Strip off the shape symbol from the constraint term.
      constraintTerm = MutableTerm(constraintTerm.begin(),
                                   constraintTerm.end() - 1);
    }

    auto constraintType = Map.getTypeForTerm(constraintTerm, GenericParams);
    Components[rule.getRHS()].Members.push_back(constraintType);
  };

  if (Debug) {
    llvm::dbgs() << "\nMinimized rules:\n";
  }

  // Build the list of requirements, storing same-type requirements off
  // to the side.
  for (unsigned ruleID : rules) {
    const auto &rule = System.getRule(ruleID);

    if (Debug) {
      llvm::dbgs() << "- " << rule << "\n";
    }

    createRequirementFromRule(rule);
  }
}

void RequirementBuilder::addTypeAliasRules(ArrayRef<unsigned> rules) {
  for (unsigned ruleID : rules) {
    const auto &rule = System.getRule(ruleID);
    auto name = *rule.isProtocolTypeAliasRule();

    if (auto prop = rule.isPropertyRule()) {
      assert(prop->getKind() == Symbol::Kind::ConcreteType);

      // Requirements containing unresolved name symbols originate from
      // invalid code and should not appear in the generic signature.
      for (auto term : prop->getSubstitutions()) {
        if (term.containsUnresolvedSymbols())
          continue;
      }

      Type concreteType = Map.getTypeFromSubstitutionSchema(
                               prop->getConcreteType(),
                               prop->getSubstitutions(),
                               GenericParams, MutableTerm());
      if (rule.isRecursive())
        concreteType = replaceTypeParametersWithErrorTypes(concreteType);

      if (ReconstituteSugar)
        concreteType = concreteType->reconstituteSugar(/*recursive=*/true);

      auto &component = Components[rule.getRHS()];
      assert(!component.ConcreteType);
      (void) component;
      Components[rule.getRHS()].ConcreteType = concreteType;
    } else {
      Components[rule.getRHS()].Aliases.push_back(name);
    }
  }
}

void RequirementBuilder::processConnectedComponents() {
  // Now, convert each connected component into a series of same-type
  // requirements.
  for (auto &pair : Components) {
    MutableTerm subjectTerm(pair.first);
    RequirementKind kind;
    if (subjectTerm.back().getKind() == Symbol::Kind::Shape) {
      kind = RequirementKind::SameShape;
      // Strip off the shape symbol from the subject term.
      subjectTerm = MutableTerm(subjectTerm.begin(), subjectTerm.end() - 1);
    } else {
      kind = RequirementKind::SameType;
    }

    auto subjectType = Map.getTypeForTerm(subjectTerm, GenericParams);
    pair.second.buildRequirements(subjectType, kind, Reqs, Aliases);
  }
}

void RequirementBuilder::sortRequirements() {
  llvm::array_pod_sort(Reqs.begin(), Reqs.end(),
                       [](const Requirement *lhs, const Requirement *rhs) -> int {
                         return lhs->compare(*rhs);
                       });

  if (Debug) {
    llvm::dbgs() << "Requirements:\n";
    for (const auto &req : Reqs) {
      req.dump(llvm::dbgs());
      llvm::dbgs() << "\n";
    }
  }
}

void RequirementBuilder::sortTypeAliases() {
  llvm::array_pod_sort(Aliases.begin(), Aliases.end(),
                       [](const ProtocolTypeAlias *lhs,
                          const ProtocolTypeAlias *rhs) -> int {
                         return lhs->getName().compare(rhs->getName());
                       });

  if (Debug) {
    llvm::dbgs() << "\nMinimized type aliases:\n";
    for (const auto &alias : Aliases) {
      PrintOptions opts;
      opts.ProtocolQualifiedDependentMemberTypes = true;

      llvm::dbgs() << "- " << alias.getName() << " == ";
      alias.getUnderlyingType().print(llvm::dbgs(), opts);
      llvm::dbgs() << "\n";
    }
  }
}

/// Convert a list of non-permanent, non-redundant rewrite rules into a list of
/// requirements sorted in canonical order. The \p genericParams are used to
/// produce sugared types.
void
RequirementMachine::buildRequirementsFromRules(
    ArrayRef<unsigned> requirementRules,
    ArrayRef<unsigned> typeAliasRules,
    ArrayRef<GenericTypeParamType *> genericParams,
    bool reconstituteSugar,
    std::vector<Requirement> &reqs,
    std::vector<ProtocolTypeAlias> &aliases) const {
  RequirementBuilder builder(System, Map, genericParams, reconstituteSugar);

  builder.addRequirementRules(requirementRules);
  builder.addTypeAliasRules(typeAliasRules);
  builder.processConnectedComponents();
  builder.sortRequirements();
  builder.sortTypeAliases();

  reqs = std::move(builder.Reqs);
  aliases = std::move(builder.Aliases);
}