Skip to content

[ConstraintSystem] Add BindingProducer base type #19132

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Sep 6, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
205 changes: 101 additions & 104 deletions lib/Sema/CSSolver.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -527,13 +527,6 @@ bool ConstraintSystem::tryTypeVariableBindings(
bool anySolved = false;
bool sawFirstLiteralConstraint = false;

auto attemptTypeVarBinding = [&](TypeVariableBinding &binding) -> bool {
// Try to solve the system with typeVar := type
ConstraintSystem::SolverScope scope(*this);
binding.attempt(*this);
return !solveRec(solutions);
};

if (TC.getLangOpts().DebugConstraintSolver) {
auto &log = getASTContext().TypeCheckerDebug->getStream();
log.indent(solverState->depth * 2) << "Initial bindings: ";
Expand All @@ -556,7 +549,7 @@ bool ConstraintSystem::tryTypeVariableBindings(
if (anySolved) {
// If this is a defaultable binding and we have found solutions,
// don't explore the default binding.
if (binding->isDefaultableBinding())
if (binding->isDefaultable())
continue;

// If we were able to solve this without considering
Expand All @@ -567,16 +560,20 @@ bool ConstraintSystem::tryTypeVariableBindings(

if (TC.getLangOpts().DebugConstraintSolver) {
auto &log = getASTContext().TypeCheckerDebug->getStream();
log.indent(solverState->depth * 2)
<< "(trying " << typeVar->getString()
<< " := " << binding->getType()->getString() << '\n';
log.indent(solverState->depth * 2) << "(trying ";
binding->print(log, &getASTContext().SourceMgr);
log << '\n';
}

if (binding->hasDefaultedProtocol())
sawFirstLiteralConstraint = true;

if (attemptTypeVarBinding(*binding))
anySolved = true;
{
// Try to solve the system with typeVar := type
ConstraintSystem::SolverScope scope(*this);
binding->attempt(*this);
anySolved |= !solveRec(solutions);
}

if (TC.getLangOpts().DebugConstraintSolver) {
auto &log = getASTContext().TypeCheckerDebug->getStream();
Expand Down Expand Up @@ -1617,17 +1614,17 @@ void ConstraintSystem::collectDisjunctions(
}

/// \brief Check if the given disjunction choice should be attempted by solver.
static bool shouldSkipDisjunctionChoice(DisjunctionChoice &choice,
static bool shouldSkipDisjunctionChoice(ConstraintSystem &cs,
const TypeBinding &choice,
Optional<Score> &bestNonGenericScore) {
auto &cs = choice.getCS();
auto &TC = cs.TC;

if (choice->isDisabled()) {
if (choice.isDisabled()) {
if (TC.getLangOpts().DebugConstraintSolver) {
auto &log = cs.getASTContext().TypeCheckerDebug->getStream();
log.indent(cs.solverState->depth)
<< "(skipping ";
choice->print(log, &TC.Context.SourceMgr);
choice.print(log, &TC.Context.SourceMgr);
log << '\n';
}

Expand Down Expand Up @@ -1746,22 +1743,68 @@ Constraint *ConstraintSystem::selectDisjunction() {
return nullptr;
}

bool ConstraintSystem::solveForDisjunctionChoices(
DisjunctionChoiceProducer &disjunction,
Optional<Score> ConstraintSystem::solveForDisjunctionChoice(
const TypeBinding &choice, ConstraintLocator *disjunctionLocator,
SmallVectorImpl<Solution> &solutions) {
SolverScope scope(*this);
++solverState->NumDisjunctionTerms;

// If the disjunction requested us to, remember which choice we
// took for it.
if (disjunctionLocator) {
auto index = choice.getIndex();
DisjunctionChoices.push_back({disjunctionLocator, index});

// Implicit unwraps of optionals are worse solutions than those
// not involving implicit unwraps.
if (!disjunctionLocator->getPath().empty()) {
auto kind = disjunctionLocator->getPath().back().getKind();
if (kind == ConstraintLocator::ImplicitlyUnwrappedDisjunctionChoice ||
kind == ConstraintLocator::DynamicLookupResult) {
assert(index == 0 || index == 1);
if (index == 1)
increaseScore(SK_ForceUnchecked);
}
}
}

choice.attempt(*this);
if (solveRec(solutions))
return None;

assert(!solutions.empty());
Score bestScore = solutions.front().getFixedScore();
if (solutions.size() == 1)
return bestScore;

for (unsigned i = 1, n = solutions.size(); i != n; ++i) {
auto &score = solutions[i].getFixedScore();
if (score < bestScore)
bestScore = score;
}

return bestScore;
}

bool ConstraintSystem::solveForDisjunctionChoices(
ArrayRef<Constraint *> choices, ConstraintLocator *disjunctionLocator,
bool isExplicitConversion, SmallVectorImpl<Solution> &solutions) {
Optional<Score> bestNonGenericScore;
Optional<std::pair<DisjunctionChoice, Score>> lastSolvedChoice;
Optional<std::pair<Constraint *, Score>> lastSolvedChoice;

DisjunctionChoiceProducer producer(*this, choices, disjunctionLocator,
isExplicitConversion);

// Try each of the constraints within the disjunction.
while (auto binding = disjunction()) {
auto &currentChoice = *binding;
if (shouldSkipDisjunctionChoice(currentChoice, bestNonGenericScore))
while (auto currentChoice = producer()) {
if (shouldSkipDisjunctionChoice(*this, *currentChoice, bestNonGenericScore))
continue;

// We already have a solution; check whether we should
// short-circuit the disjunction.
if (lastSolvedChoice) {
Constraint *lastChoice = lastSolvedChoice->first;
auto *choice = choices[currentChoice->getIndex()];
auto *lastChoice = lastSolvedChoice->first;
auto delta = lastSolvedChoice->second - CurrentScore;
bool hasUnavailableOverloads = delta.Data[SK_Unavailable] > 0;
bool hasFixes = delta.Data[SK_Fix] > 0;
Expand All @@ -1771,13 +1814,10 @@ bool ConstraintSystem::solveForDisjunctionChoices(
// selecting unavailable overloads or result in fixes being
// applied to reach a solution.
if (!hasUnavailableOverloads && !hasFixes &&
shortCircuitDisjunctionAt(currentChoice, lastChoice, getASTContext()))
shortCircuitDisjunctionAt(choice, lastChoice, getASTContext()))
break;
}

// Try to solve the system with this option in the disjunction.
SolverScope scope(*this);
++solverState->NumDisjunctionTerms;
if (TC.getLangOpts().DebugConstraintSolver) {
auto &log = getASTContext().TypeCheckerDebug->getStream();
log.indent(solverState->depth)
Expand All @@ -1786,34 +1826,16 @@ bool ConstraintSystem::solveForDisjunctionChoices(
log << '\n';
}

// If the disjunction requested us to, remember which choice we
// took for it.

if (auto *disjunctionLocator = disjunction.getLocator()) {
auto index = currentChoice.getIndex();
DisjunctionChoices.push_back({disjunctionLocator, index});

// Implicit unwraps of optionals are worse solutions than those
// not involving implicit unwraps.
if (!disjunctionLocator->getPath().empty()) {
auto kind = disjunctionLocator->getPath().back().getKind();
if (kind == ConstraintLocator::ImplicitlyUnwrappedDisjunctionChoice ||
kind == ConstraintLocator::DynamicLookupResult) {
assert(index == 0 || index == 1);
if (index == 1)
increaseScore(SK_ForceUnchecked);
}
}
}

if (auto score = binding->attempt(solutions)) {
if (!currentChoice.isGenericOperator() &&
currentChoice.isSymmetricOperator()) {
// Try to solve the system with this option in the disjunction.
if (auto score = solveForDisjunctionChoice(*currentChoice,
disjunctionLocator, solutions)) {
if (!currentChoice->isGenericOperator() &&
currentChoice->isSymmetricOperator()) {
if (!bestNonGenericScore || score < bestNonGenericScore)
bestNonGenericScore = score;
}

lastSolvedChoice = {currentChoice, *score};
lastSolvedChoice = {choices[currentChoice->getIndex()], *score};
}

if (TC.getLangOpts().DebugConstraintSolver) {
Expand Down Expand Up @@ -1882,11 +1904,9 @@ bool ConstraintSystem::solveForDisjunction(
disjunction->shouldRememberChoice() ? disjunction->getLocator() : nullptr;
assert(!disjunction->shouldRememberChoice() || disjunction->getLocator());

auto choices =
DisjunctionChoiceProducer(*this, disjunction->getNestedConstraints(),
locator, disjunction->isExplicitConversion());

auto noSolutions = solveForDisjunctionChoices(choices, solutions);
auto noSolutions = solveForDisjunctionChoices(
disjunction->getNestedConstraints(), locator,
disjunction->isExplicitConversion(), solutions);

if (hasDisabledChoices) {
// Re-enable previously disabled overload choices.
Expand Down Expand Up @@ -1956,46 +1976,23 @@ bool ConstraintSystem::solveSimplified(SmallVectorImpl<Solution> &solutions) {
}

void DisjunctionChoice::attempt(ConstraintSystem &cs) const {
CS->simplifyDisjunctionChoice(Choice);
cs.simplifyDisjunctionChoice(Choice);

if (ExplicitConversion)
propagateConversionInfo();
}

Optional<Score>
DisjunctionChoice::attempt(SmallVectorImpl<Solution> &solutions) {
attempt(*CS);

if (CS->solveRec(solutions))
return None;

assert (!solutions.empty());

Score bestScore = solutions.front().getFixedScore();

if (solutions.size() == 1)
return bestScore;

for (unsigned i = 1, n = solutions.size(); i != n; ++i) {
auto &score = solutions[i].getFixedScore();
if (score < bestScore)
bestScore = score;
}

return bestScore;
propagateConversionInfo(cs);
}

bool DisjunctionChoice::isGenericOperator() const {
auto *decl = getOperatorDecl();
bool DisjunctionChoice::isGenericOp(Constraint *choice) {
auto *decl = getOperatorDecl(choice);
if (!decl)
return false;

auto interfaceType = decl->getInterfaceType();
return interfaceType->is<GenericFunctionType>();
}

bool DisjunctionChoice::isSymmetricOperator() const {
auto *decl = getOperatorDecl();
bool DisjunctionChoice::isSymmetricOp(Constraint *choice) {
auto *decl = getOperatorDecl(choice);
if (!decl)
return false;

Expand All @@ -2009,7 +2006,7 @@ bool DisjunctionChoice::isSymmetricOperator() const {
return firstType->isEqual(secondType);
}

void DisjunctionChoice::propagateConversionInfo() const {
void DisjunctionChoice::propagateConversionInfo(ConstraintSystem &cs) const {
assert(ExplicitConversion);

auto LHS = Choice->getFirstType();
Expand All @@ -2026,28 +2023,28 @@ void DisjunctionChoice::propagateConversionInfo() const {
if (typeVar->getImpl().getFixedType(nullptr))
return;

auto bindings = CS->getPotentialBindings(typeVar);
auto bindings = cs.getPotentialBindings(typeVar);
if (bindings.InvolvesTypeVariables || bindings.Bindings.size() != 1)
return;

auto conversionType = bindings.Bindings[0].BindingType;
llvm::SetVector<Constraint *> constraints;
CS->CG.gatherConstraints(typeVar, constraints,
ConstraintGraph::GatheringKind::EquivalenceClass,
[](Constraint *constraint) -> bool {
switch (constraint->getKind()) {
case ConstraintKind::Conversion:
case ConstraintKind::Defaultable:
case ConstraintKind::ConformsTo:
case ConstraintKind::LiteralConformsTo:
return false;

default:
return true;
}
});
cs.CG.gatherConstraints(typeVar, constraints,
ConstraintGraph::GatheringKind::EquivalenceClass,
[](Constraint *constraint) -> bool {
switch (constraint->getKind()) {
case ConstraintKind::Conversion:
case ConstraintKind::Defaultable:
case ConstraintKind::ConformsTo:
case ConstraintKind::LiteralConformsTo:
return false;

default:
return true;
}
});

if (constraints.empty())
CS->addConstraint(ConstraintKind::Bind, typeVar, conversionType,
Choice->getLocator());
cs.addConstraint(ConstraintKind::Bind, typeVar, conversionType,
Choice->getLocator());
}
Loading