Skip to content

[ConstraintSystem] Enforce TVO_CanBindToPack, and diagnose pack references outside of pack expansion expressions. #64498

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 1 commit into from
Mar 21, 2023
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
5 changes: 3 additions & 2 deletions include/swift/AST/DiagnosticsSema.def
Original file line number Diff line number Diff line change
Expand Up @@ -5317,8 +5317,9 @@ ERROR(expansion_not_allowed,none,
ERROR(expansion_not_variadic,none,
"pack expansion %0 must contain at least one pack reference", (Type))
ERROR(pack_reference_outside_expansion,none,
"pack reference %0 can only appear in pack expansion or generic requirement",
(Type))
"pack reference %0 can only appear in pack expansion "
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not a fan of this error message, bike-shedding is welcome!

"%select{or generic requirement|}1",
(Type, /*inExpression*/ bool))
ERROR(each_non_pack,none,
"'each' cannot be applied to non-pack type %0",
(Type))
Expand Down
27 changes: 27 additions & 0 deletions include/swift/Sema/CSFix.h
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,9 @@ enum class FixKind : uint8_t {

/// Allow 'each' applied to a non-pack type.
AllowInvalidPackElement,

/// Allow pack references outside of pack expansions.
AllowInvalidPackReference,
};

class ConstraintFix {
Expand Down Expand Up @@ -2099,6 +2102,30 @@ class AllowInvalidPackElement final : public ConstraintFix {
}
};

class AllowInvalidPackReference final : public ConstraintFix {
Type packType;

AllowInvalidPackReference(ConstraintSystem &cs, Type packType,
ConstraintLocator *locator)
: ConstraintFix(cs, FixKind::AllowInvalidPackReference, locator),
packType(packType) {}

public:
std::string getName() const override {
return "allow pack outside pack expansion";
}

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

static AllowInvalidPackReference *create(ConstraintSystem &cs,
Type packType,
ConstraintLocator *locator);

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

class CollectionElementContextualMismatch final
: public ContextualMismatch,
private llvm::TrailingObjects<CollectionElementContextualMismatch,
Expand Down
6 changes: 6 additions & 0 deletions lib/Sema/CSDiagnostics.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6146,6 +6146,12 @@ bool InvalidPackElement::diagnoseAsError() {
return true;
}

bool InvalidPackReference::diagnoseAsError() {
emitDiagnostic(diag::pack_reference_outside_expansion,
packType, /*inExpression*/true);
return true;
}

bool CollectionElementContextualFailure::diagnoseAsError() {
auto anchor = getRawAnchor();
auto *locator = getLocator();
Expand Down
13 changes: 13 additions & 0 deletions lib/Sema/CSDiagnostics.h
Original file line number Diff line number Diff line change
Expand Up @@ -1851,6 +1851,19 @@ class InvalidPackElement final : public FailureDiagnostic {
bool diagnoseAsError() override;
};

/// Diagnose pack references outside of pack expansion expressions.
class InvalidPackReference final : public FailureDiagnostic {
Type packType;

public:
InvalidPackReference(const Solution &solution, Type packType,
ConstraintLocator *locator)
: FailureDiagnostic(solution, locator),
packType(packType) {}

bool diagnoseAsError() override;
};

/// Diagnose a contextual mismatch between expected collection element type
/// and the one provided (e.g. source of the assignment or argument to a call)
/// e.g.:
Expand Down
13 changes: 13 additions & 0 deletions lib/Sema/CSFix.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1401,6 +1401,19 @@ AllowInvalidPackElement::create(ConstraintSystem &cs,
AllowInvalidPackElement(cs, packElementType, locator);
}

bool AllowInvalidPackReference::diagnose(const Solution &solution,
bool asNote) const {
InvalidPackReference failure(solution, packType, getLocator());
return failure.diagnose(asNote);
}

AllowInvalidPackReference *
AllowInvalidPackReference::create(ConstraintSystem &cs, Type packType,
ConstraintLocator *locator) {
return new (cs.getAllocator())
AllowInvalidPackReference(cs, packType, locator);
}

bool CollectionElementContextualMismatch::diagnose(const Solution &solution,
bool asNote) const {
CollectionElementContextualFailure failure(
Expand Down
27 changes: 21 additions & 6 deletions lib/Sema/CSGen.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -923,9 +923,14 @@ namespace {
CS.getConstraintLocator(expr, ConstraintLocator::Member),
TVO_CanBindToHole);
}
unsigned options = (TVO_CanBindToLValue |
TVO_CanBindToNoEscape);
if (!PackElementEnvironments.empty())
options |= TVO_CanBindToPack;

auto tv = CS.createTypeVariable(
CS.getConstraintLocator(expr, ConstraintLocator::Member),
TVO_CanBindToLValue | TVO_CanBindToNoEscape);
options);
SmallVector<OverloadChoice, 4> outerChoices;
for (auto decl : outerAlternatives) {
outerChoices.push_back(OverloadChoice(Type(), decl, functionRefKind));
Expand Down Expand Up @@ -1419,11 +1424,14 @@ namespace {
return invalidateReference();
}

unsigned options = (TVO_CanBindToLValue |
TVO_CanBindToNoEscape);
if (!PackElementEnvironments.empty())
options |= TVO_CanBindToPack;

// Create an overload choice referencing this declaration and immediately
// resolve it. This records the overload for use later.
auto tv = CS.createTypeVariable(locator,
TVO_CanBindToLValue |
TVO_CanBindToNoEscape);
auto tv = CS.createTypeVariable(locator, options);

OverloadChoice choice =
OverloadChoice(Type(), E->getDecl(), E->getFunctionRefKind());
Expand Down Expand Up @@ -3099,8 +3107,15 @@ namespace {
Type visitPackElementExpr(PackElementExpr *expr) {
auto packType = CS.getType(expr->getPackRefExpr());

if (PackElementEnvironments.empty())
return Type();
// If 'each t' is written outside of a pack expansion expression, allow the
// type to bind to a hole. The invalid pack reference will be diagnosed when
// attempting to bind the type variable for the underlying pack reference to
// a pack type without TVO_CanBindToPack.
if (PackElementEnvironments.empty()) {
return CS.createTypeVariable(CS.getConstraintLocator(expr),
TVO_CanBindToHole |
TVO_CanBindToNoEscape);
}

// The type of a PackElementExpr is the opened pack element archetype
// of the pack reference.
Expand Down
18 changes: 18 additions & 0 deletions lib/Sema/CSSimplify.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4294,6 +4294,23 @@ ConstraintSystem::matchTypesBindTypeVar(
}
}

// If we're attempting to bind a PackType or PackArchetypeType to a type
// variable that doesn't support it, we have a pack reference outside of a
// pack expansion expression.
if (!typeVar->getImpl().canBindToPack() &&
(type->is<PackArchetypeType>() || type->is<PackType>())) {
if (shouldAttemptFixes()) {
auto *fix = AllowInvalidPackReference::create(*this, type,
getConstraintLocator(locator));
if (!recordFix(fix)) {
recordPotentialHole(typeVar);
return getTypeMatchSuccess();
}
}

return getTypeMatchFailure(locator);
}

// We do not allow keypaths to go through AnyObject. Let's create a fix
// so this can be diagnosed later.
if (auto loc = typeVar->getImpl().getLocator()) {
Expand Down Expand Up @@ -14151,6 +14168,7 @@ ConstraintSystem::SolutionKind ConstraintSystem::simplifyFixConstraint(
case FixKind::RenameConflictingPatternVariables:
case FixKind::MustBeCopyable:
case FixKind::AllowInvalidPackElement:
case FixKind::AllowInvalidPackReference:
case FixKind::MacroMissingPound:
case FixKind::AllowGlobalActorMismatch:
case FixKind::GenericArgumentsMismatch: {
Expand Down
2 changes: 1 addition & 1 deletion lib/Sema/TypeCheckType.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4598,7 +4598,7 @@ NeverNullType TypeResolver::resolvePackElement(PackElementTypeRepr *repr,
if (!options.contains(TypeResolutionFlags::AllowPackReferences)) {
ctx.Diags.diagnose(repr->getLoc(),
diag::pack_reference_outside_expansion,
packReference);
packReference, /*inExpression*/false);
return ErrorType::get(ctx);
}

Expand Down
22 changes: 22 additions & 0 deletions test/Constraints/pack-expansion-expressions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -202,3 +202,25 @@ func takesFunctionPack<each T, R>(functions: repeat ((each T) -> R)) {}
func forwardFunctionPack<each T>(functions: repeat (each T) -> Bool) {
takesFunctionPack(functions: repeat each functions)
}

func packOutsideExpansion<each T>(_ t: repeat each T) {
_ = t
// expected-error@-1{{pack reference 'T' can only appear in pack expansion}}

forward(t)
// expected-error@-1{{pack reference 'T' can only appear in pack expansion}}

_ = each t
// expected-error@-1{{pack reference 'T' can only appear in pack expansion}}

forward(each t)
// expected-error@-1{{pack reference 'T' can only appear in pack expansion}}

let tuple = (repeat each t)

_ = tuple.element
// expected-error@-1{{pack reference 'T' can only appear in pack expansion}}

_ = each tuple.element
// expected-error@-1{{pack reference 'T' can only appear in pack expansion}}
}