Skip to content

[Diagnostics] Diagnose conflicting pattern variables #59210

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 3 commits into from
Jun 14, 2022
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
48 changes: 48 additions & 0 deletions include/swift/Sema/CSFix.h
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,10 @@ enum class FixKind : uint8_t {
/// Coerce a result type of a call to a particular existential type
/// by adding `as any <#Type#>`.
AddExplicitExistentialCoercion,

/// For example `.a(let x), .b(let x)` where `x` gets bound to different
/// types.
RenameConflictingPatternVariables,
};

class ConstraintFix {
Expand Down Expand Up @@ -3016,6 +3020,50 @@ class AddExplicitExistentialCoercion final : public ConstraintFix {
ConstraintLocator *locator);
};

class RenameConflictingPatternVariables final
: public ConstraintFix,
private llvm::TrailingObjects<RenameConflictingPatternVariables,
VarDecl *> {
friend TrailingObjects;

Type ExpectedType;
unsigned NumConflicts;

RenameConflictingPatternVariables(ConstraintSystem &cs, Type expectedTy,
ArrayRef<VarDecl *> conflicts,
ConstraintLocator *locator)
: ConstraintFix(cs, FixKind::RenameConflictingPatternVariables, locator),
ExpectedType(expectedTy), NumConflicts(conflicts.size()) {
std::uninitialized_copy(conflicts.begin(), conflicts.end(),
getConflictingBuffer().begin());
}

MutableArrayRef<VarDecl *> getConflictingBuffer() {
return {getTrailingObjects<VarDecl *>(), NumConflicts};
}

public:
std::string getName() const override { return "rename pattern variables"; }

ArrayRef<VarDecl *> getConflictingVars() const {
return {getTrailingObjects<VarDecl *>(), NumConflicts};
}

bool diagnose(const Solution &solution, bool asNote = false) const override;

bool diagnoseForAmbiguity(CommonFixesArray commonFixes) const override {
return diagnose(*commonFixes.front().first);
}

static RenameConflictingPatternVariables *
create(ConstraintSystem &cs, Type expectedTy, ArrayRef<VarDecl *> conflicts,
ConstraintLocator *locator);

static bool classof(ConstraintFix *fix) {
return fix->getKind() == FixKind::RenameConflictingPatternVariables;
}
};

} // end namespace constraints
} // end namespace swift

Expand Down
81 changes: 75 additions & 6 deletions lib/Sema/CSClosure.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,8 @@ class SyntacticElementConstraintGenerator
hadError = true;
return;
}

caseItem->setPattern(pattern, /*resolved=*/true);
}

// Let's generate constraints for pattern + where clause.
Expand Down Expand Up @@ -774,8 +776,6 @@ class SyntacticElementConstraintGenerator
}
}

bindSwitchCasePatternVars(context.getAsDeclContext(), caseStmt);

auto *caseLoc = cs.getConstraintLocator(
locator, LocatorPathElt::SyntacticElement(caseStmt));

Expand All @@ -799,10 +799,8 @@ class SyntacticElementConstraintGenerator
locator->castLastElementTo<LocatorPathElt::SyntacticElement>()
.asStmt());

for (auto caseBodyVar : caseStmt->getCaseBodyVariablesOrEmptyArray()) {
auto parentVar = caseBodyVar->getParentVarDecl();
assert(parentVar && "Case body variables always have parents");
cs.setType(caseBodyVar, cs.getType(parentVar));
if (recordInferredSwitchCasePatternVars(caseStmt)) {
hadError = true;
}
}

Expand Down Expand Up @@ -929,6 +927,75 @@ class SyntacticElementConstraintGenerator
locator->getLastElementAs<LocatorPathElt::SyntacticElement>();
return parentElt ? parentElt->getElement().isStmt(kind) : false;
}

bool recordInferredSwitchCasePatternVars(CaseStmt *caseStmt) {
llvm::SmallDenseMap<Identifier, SmallVector<VarDecl *, 2>, 4> patternVars;

auto recordVar = [&](VarDecl *var) {
if (!var->hasName())
return;
patternVars[var->getName()].push_back(var);
};

for (auto &caseItem : caseStmt->getMutableCaseLabelItems()) {
assert(caseItem.isPatternResolved());

auto *pattern = caseItem.getPattern();
pattern->forEachVariable([&](VarDecl *var) { recordVar(var); });
}

for (auto bodyVar : caseStmt->getCaseBodyVariablesOrEmptyArray()) {
if (!bodyVar->hasName())
continue;

const auto &variants = patternVars[bodyVar->getName()];

auto getType = [&](VarDecl *var) {
auto type = cs.simplifyType(cs.getType(var));
assert(!type->hasTypeVariable());
return type;
};

switch (variants.size()) {
case 0:
break;

case 1:
// If there is only one choice here, let's use it directly.
cs.setType(bodyVar, getType(variants.front()));
break;

default: {
// If there are multiple choices it could only mean multiple
// patterns e.g. `.a(let x), .b(let x), ...:`. Let's join them.
Type joinType = getType(variants.front());

SmallVector<VarDecl *, 2> conflicts;
for (auto *var : llvm::drop_begin(variants)) {
auto varType = getType(var);
// Type mismatch between different patterns.
if (!joinType->isEqual(varType))
conflicts.push_back(var);
}

if (!conflicts.empty()) {
if (!cs.shouldAttemptFixes())
return true;

// dfdf
auto *locator = cs.getConstraintLocator(bodyVar);
if (cs.recordFix(RenameConflictingPatternVariables::create(
cs, joinType, conflicts, locator)))
return true;
}

cs.setType(bodyVar, joinType);
}
}
}

return false;
}
};
}

Expand Down Expand Up @@ -1336,6 +1403,8 @@ class SyntacticElementSolutionApplication
}
}

bindSwitchCasePatternVars(context.getAsDeclContext(), caseStmt);

for (auto *expected : caseStmt->getCaseBodyVariablesOrEmptyArray()) {
assert(expected->hasName());
auto prev = expected->getParentVarDecl();
Expand Down
9 changes: 9 additions & 0 deletions lib/Sema/CSDiagnostics.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8212,3 +8212,12 @@ void MissingExplicitExistentialCoercion::fixIt(
"as " + ErasedResultType->getString(printOpts) +
(requiresParens ? ")" : ""));
}

bool ConflictingPatternVariables::diagnoseAsError() {
for (auto *var : Vars) {
emitDiagnosticAt(var->getStartLoc(),
diag::type_mismatch_multiple_pattern_list, getType(var),
ExpectedType);
}
return true;
}
35 changes: 35 additions & 0 deletions lib/Sema/CSDiagnostics.h
Original file line number Diff line number Diff line change
Expand Up @@ -2764,6 +2764,41 @@ class MissingExplicitExistentialCoercion final : public FailureDiagnostic {
bool fixItRequiresParens() const;
};

/// Diagnose situations where pattern variables with the same name
/// have conflicting types:
///
/// \code
/// enum E {
/// case a(Int)
/// case b(String)
/// }
///
/// func test(e: E) {
/// switch e {
/// case .a(let x), .b(let x): ...
/// }
/// }
/// \endcode
///
/// In this example `x` is bound to `Int` and `String` at the same
/// time which is incorrect.
class ConflictingPatternVariables final : public FailureDiagnostic {
Type ExpectedType;
SmallVector<VarDecl *, 4> Vars;

public:
ConflictingPatternVariables(const Solution &solution, Type expectedTy,
ArrayRef<VarDecl *> conflicts,
ConstraintLocator *locator)
: FailureDiagnostic(solution, locator),
ExpectedType(resolveType(expectedTy)),
Vars(conflicts.begin(), conflicts.end()) {
assert(!Vars.empty());
}

bool diagnoseAsError() override;
};

} // end namespace constraints
} // end namespace swift

Expand Down
18 changes: 18 additions & 0 deletions lib/Sema/CSFix.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2424,3 +2424,21 @@ AddExplicitExistentialCoercion::create(ConstraintSystem &cs, Type resultTy,
return new (cs.getAllocator())
AddExplicitExistentialCoercion(cs, resultTy, locator);
}

bool RenameConflictingPatternVariables::diagnose(const Solution &solution,
bool asNote) const {
ConflictingPatternVariables failure(solution, ExpectedType,
getConflictingVars(), getLocator());
return failure.diagnose(asNote);
}

RenameConflictingPatternVariables *
RenameConflictingPatternVariables::create(ConstraintSystem &cs, Type expectedTy,
ArrayRef<VarDecl *> conflicts,
ConstraintLocator *locator) {
unsigned size = totalSizeToAlloc<VarDecl *>(conflicts.size());
void *mem = cs.getAllocator().Allocate(
size, alignof(RenameConflictingPatternVariables));
return new (mem)
RenameConflictingPatternVariables(cs, expectedTy, conflicts, locator);
}
3 changes: 2 additions & 1 deletion lib/Sema/CSSimplify.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12908,7 +12908,8 @@ ConstraintSystem::SolutionKind ConstraintSystem::simplifyFixConstraint(
case FixKind::SpecifyTypeForPlaceholder:
case FixKind::AllowAutoClosurePointerConversion:
case FixKind::IgnoreKeyPathContextualMismatch:
case FixKind::NotCompileTimeConst: {
case FixKind::NotCompileTimeConst:
case FixKind::RenameConflictingPatternVariables: {
return recordFix(fix) ? SolutionKind::Error : SolutionKind::Solved;
}

Expand Down
32 changes: 32 additions & 0 deletions test/expr/closure/multi_statement.swift
Original file line number Diff line number Diff line change
Expand Up @@ -515,3 +515,35 @@ func test_missing_conformance_diagnostics_in_for_sequence() {
}
}
}

func test_conflicting_pattern_vars() {
enum E {
case a(Int, String)
case b(String, Int)
}

func fn(_: (E) -> Void) {}
func fn<T>(_: (E) -> T) {}

func test(e: E) {
fn {
switch $0 {
case .a(let x, let y),
.b(let x, let y):
// expected-error@-1 {{pattern variable bound to type 'String', expected type 'Int'}}
// expected-error@-2 {{pattern variable bound to type 'Int', expected type 'String'}}
_ = x
_ = y
}
}

fn {
switch $0 {
case .a(let x, let y),
.b(let y, let x): // Ok
_ = x
_ = y
}
}
}
}