Skip to content

[ConstraintSystem] implement implicit pack materialization for abstract tuples instead of explicit '.element' #67292

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
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
1 change: 0 additions & 1 deletion include/swift/AST/KnownIdentifiers.def
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,6 @@ IDENTIFIER(size)
IDENTIFIER(speed)
IDENTIFIER(unchecked)
IDENTIFIER(unsafe)
IDENTIFIER(element)

// The singleton instance of TupleTypeDecl in the Builtin module
IDENTIFIER(TheTupleType)
Expand Down
4 changes: 4 additions & 0 deletions include/swift/Sema/Constraint.h
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,9 @@ enum class ConstraintKind : char {
ExplicitGenericArguments,
/// Both (first and second) pack types should have the same reduced shape.
SameShape,
/// The first type is a tuple containing a single unlabeled element that is a
/// pack expansion. The second type is that pack expansion.
MaterializePackExpansion,
};

/// Classification of the different kinds of constraints.
Expand Down Expand Up @@ -703,6 +706,7 @@ class Constraint final : public llvm::ilist_node<Constraint>,
case ConstraintKind::UnresolvedMemberChainBase:
case ConstraintKind::PackElementOf:
case ConstraintKind::SameShape:
case ConstraintKind::MaterializePackExpansion:
return ConstraintClassification::Relational;

case ConstraintKind::ValueMember:
Expand Down
13 changes: 12 additions & 1 deletion include/swift/Sema/ConstraintSystem.h
Original file line number Diff line number Diff line change
Expand Up @@ -4987,6 +4987,13 @@ class ConstraintSystem {
TypeMatchOptions flags,
ConstraintLocatorBuilder locator);

/// Remove the tuple wrapping of left-hand type if it contains only a single
/// unlabeled element that is a pack expansion.
SolutionKind
simplifyMaterializePackExpansionConstraint(Type type1, Type type2,
TypeMatchOptions flags,
ConstraintLocatorBuilder locator);

public: // FIXME: Public for use by static functions.
/// Simplify a conversion constraint with a fix applied to it.
SolutionKind simplifyFixConstraint(ConstraintFix *fix, Type type1, Type type2,
Expand Down Expand Up @@ -5546,7 +5553,8 @@ class OpenPackElementType {
}

cs.addConstraint(ConstraintKind::PackElementOf, elementType,
packType, cs.getConstraintLocator(elementEnv));
packType->getRValueType(),
cs.getConstraintLocator(elementEnv));
return elementType;
}
};
Expand Down Expand Up @@ -6229,6 +6237,9 @@ void dumpAnchor(ASTNode anchor, SourceManager *SM, raw_ostream &out);

bool isSingleUnlabeledPackExpansionTuple(Type type);

/// \returns null if \c type is not a single unlabeled pack expansion tuple.
Type getPatternTypeOfSingleUnlabeledPackExpansionTuple(Type type);

} // end namespace constraints

template<typename ...Args>
Expand Down
5 changes: 2 additions & 3 deletions lib/Sema/CSApply.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3860,9 +3860,8 @@ namespace {
auto packRefType = cs.getType(packRefExpr);
if (auto *tuple = packRefType->getRValueType()->getAs<TupleType>();
tuple && tuple->isSingleUnlabeledPackExpansion()) {
auto *expansion =
tuple->getElementType(0)->castTo<PackExpansionType>();
auto patternType = expansion->getPatternType();
auto patternType =
getPatternTypeOfSingleUnlabeledPackExpansionTuple(tuple);
auto *materializedPackExpr = MaterializePackExpr::create(
cs.getASTContext(), packRefExpr, packRefExpr->getLoc(),
patternType, /*implicit*/ true);
Expand Down
1 change: 1 addition & 0 deletions lib/Sema/CSBindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1483,6 +1483,7 @@ void PotentialBindings::infer(Constraint *constraint) {
case ConstraintKind::ExplicitGenericArguments:
case ConstraintKind::PackElementOf:
case ConstraintKind::SameShape:
case ConstraintKind::MaterializePackExpansion:
// Constraints from which we can't do anything.
break;

Expand Down
6 changes: 4 additions & 2 deletions lib/Sema/CSDiagnostics.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6229,8 +6229,10 @@ bool InvalidPackElement::diagnoseAsError() {
}

bool InvalidPackReference::diagnoseAsError() {
emitDiagnostic(diag::pack_reference_outside_expansion,
packType);
auto patternType =
getPatternTypeOfSingleUnlabeledPackExpansionTuple(packType);
Copy link
Contributor

Choose a reason for hiding this comment

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

One note because I'll forget and it could totally be done separately - both InvalidPackReference and InvalidPackElement constructors should use resolveType(packType) and resolveType(packElementType) accordingly instead of just packType and packElementType, otherwise we'd end up with a diagnostic that could have type variables in it and crash.

auto diagnosisType = patternType ? patternType : packType;
emitDiagnostic(diag::pack_reference_outside_expansion, diagnosisType);
return true;
}

Expand Down
40 changes: 23 additions & 17 deletions lib/Sema/CSGen.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1146,10 +1146,6 @@ struct VarRefCollector : public ASTWalker {

Type openPackElement(Type packType, ConstraintLocator *locator,
PackExpansionExpr *packElementEnvironment) {
// 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 (!packElementEnvironment) {
return CS.createTypeVariable(locator,
TVO_CanBindToHole | TVO_CanBindToNoEscape);
Expand Down Expand Up @@ -3127,8 +3123,14 @@ struct VarRefCollector : public ASTWalker {
llvm_unreachable("unsupported pack reference ASTNode");
}

auto *elementShape = CS.createTypeVariable(
CS.getConstraintLocator(pack, ConstraintLocator::PackShape),
TVO_CanBindToPack);
CS.addConstraint(
ConstraintKind::ShapeOf, expansionType->getCountType(), packType,
ConstraintKind::ShapeOf, elementShape, packType,
CS.getConstraintLocator(pack, ConstraintLocator::PackShape));
CS.addConstraint(
ConstraintKind::Equal, elementShape, expansionType->getCountType(),
CS.getConstraintLocator(expr, ConstraintLocator::PackShape));
}

Expand All @@ -3137,27 +3139,31 @@ struct VarRefCollector : public ASTWalker {

Type visitPackElementExpr(PackElementExpr *expr) {
auto packType = CS.getType(expr->getPackRefExpr());

if (isSingleUnlabeledPackExpansionTuple(packType)) {
packType =
addMemberRefConstraints(expr, expr->getPackRefExpr(),
DeclNameRef(CS.getASTContext().Id_element),
FunctionRefKind::Unapplied, {});
CS.setType(expr->getPackRefExpr(), packType);
}

auto *packEnvironment = CS.getPackEnvironment(expr);
auto elementType = openPackElement(
packType, CS.getConstraintLocator(expr), packEnvironment);
if (packEnvironment) {
auto expansionType =
CS.getType(packEnvironment)->castTo<PackExpansionType>();
CS.addConstraint(ConstraintKind::ShapeOf, expansionType->getCountType(),
packType,
elementType,
CS.getConstraintLocator(packEnvironment,
ConstraintLocator::PackShape));
auto *elementShape = CS.createTypeVariable(
CS.getConstraintLocator(expr, ConstraintLocator::PackShape),
TVO_CanBindToPack);
CS.addConstraint(
ConstraintKind::ShapeOf, elementShape, elementType,
CS.getConstraintLocator(expr, ConstraintLocator::PackShape));
CS.addConstraint(
ConstraintKind::Equal, elementShape, expansionType->getCountType(),
CS.getConstraintLocator(expr, ConstraintLocator::PackShape));
} else {
CS.recordFix(AllowInvalidPackReference::create(
CS, packType, CS.getConstraintLocator(expr->getPackRefExpr())));
}

return openPackElement(packType, CS.getConstraintLocator(expr),
packEnvironment);
return elementType;
}

Type visitMaterializePackExpr(MaterializePackExpr *expr) {
Expand Down
82 changes: 71 additions & 11 deletions lib/Sema/CSSimplify.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -129,12 +129,20 @@ static bool isPackExpansionType(Type type) {

bool constraints::isSingleUnlabeledPackExpansionTuple(Type type) {
auto *tuple = type->getRValueType()->getAs<TupleType>();
// TODO: drop no name requirement
return tuple && (tuple->getNumElements() == 1) &&
isPackExpansionType(tuple->getElementType(0)) &&
!tuple->getElement(0).hasName();
}

Type constraints::getPatternTypeOfSingleUnlabeledPackExpansionTuple(Type type) {
if (!isSingleUnlabeledPackExpansionTuple(type)) {
return {};
}
auto tuple = type->getRValueType()->castTo<TupleType>();
auto *expansion = tuple->getElementType(0)->castTo<PackExpansionType>();
return expansion->getPatternType();
}

static bool containsPackExpansionType(ArrayRef<AnyFunctionType::Param> params) {
return llvm::any_of(params, [&](const auto &param) {
return isPackExpansionType(param.getPlainType());
Expand Down Expand Up @@ -2283,6 +2291,7 @@ ConstraintSystem::matchTupleTypes(TupleType *tuple1, TupleType *tuple2,
case ConstraintKind::ShapeOf:
case ConstraintKind::ExplicitGenericArguments:
case ConstraintKind::SameShape:
case ConstraintKind::MaterializePackExpansion:
llvm_unreachable("Bad constraint kind in matchTupleTypes()");
}

Expand Down Expand Up @@ -2643,6 +2652,7 @@ static bool matchFunctionRepresentations(FunctionType::ExtInfo einfo1,
case ConstraintKind::ShapeOf:
case ConstraintKind::ExplicitGenericArguments:
case ConstraintKind::SameShape:
case ConstraintKind::MaterializePackExpansion:
return true;
}

Expand Down Expand Up @@ -3161,6 +3171,7 @@ ConstraintSystem::matchFunctionTypes(FunctionType *func1, FunctionType *func2,
case ConstraintKind::ShapeOf:
case ConstraintKind::ExplicitGenericArguments:
case ConstraintKind::SameShape:
case ConstraintKind::MaterializePackExpansion:
llvm_unreachable("Not a relational constraint");
}

Expand Down Expand Up @@ -6827,6 +6838,7 @@ ConstraintSystem::matchTypes(Type type1, Type type2, ConstraintKind kind,
case ConstraintKind::ShapeOf:
case ConstraintKind::ExplicitGenericArguments:
case ConstraintKind::SameShape:
case ConstraintKind::MaterializePackExpansion:
llvm_unreachable("Not a relational constraint");
}
}
Expand Down Expand Up @@ -9149,13 +9161,13 @@ ConstraintSystem::simplifyPackElementOfConstraint(Type first, Type second,
}

if (isSingleUnlabeledPackExpansionTuple(patternType)) {
auto *elementVar =
createTypeVariable(getConstraintLocator(locator), /*options=*/0);
addValueMemberConstraint(
patternType, DeclNameRef(getASTContext().Id_element), elementVar, DC,
FunctionRefKind::Unapplied, {},
getConstraintLocator(locator, {ConstraintLocator::Member}));
patternType = elementVar;
auto *packVar =
createTypeVariable(getConstraintLocator(locator), TVO_CanBindToPack);
addConstraint(ConstraintKind::MaterializePackExpansion, patternType,
packVar,
getConstraintLocator(locator, {ConstraintLocator::Member}));
addConstraint(ConstraintKind::PackElementOf, elementType, packVar, locator);
return SolutionKind::Solved;
}

// Let's try to resolve element type based on the pattern type.
Expand All @@ -9175,11 +9187,19 @@ ConstraintSystem::simplifyPackElementOfConstraint(Type first, Type second,
if (!shapeClass->is<PackArchetypeType>()) {
if (recordFix(AllowInvalidPackElement::create(*this, patternType, loc)))
return SolutionKind::Error;
} else {
auto envShape = PackExpansionEnvironments.find(loc);
if (envShape == PackExpansionEnvironments.end()) {
return SolutionKind::Error;
}
auto *fix = SkipSameShapeRequirement::create(
*this, envShape->second.second, shapeClass,
getConstraintLocator(loc, ConstraintLocator::PackShape));
if (recordFix(fix)) {
return SolutionKind::Error;
}
}

// Only other posibility is that there is a shape mismatch between
// elements of the pack expansion pattern which is detected separately.

recordAnyTypeVarAsPotentialHole(elementType);
return SolutionKind::Solved;
}
Expand Down Expand Up @@ -13552,6 +13572,37 @@ ConstraintSystem::SolutionKind ConstraintSystem::simplifySameShapeConstraint(
return SolutionKind::Error;
}

ConstraintSystem::SolutionKind
ConstraintSystem::simplifyMaterializePackExpansionConstraint(
Type type1, Type type2, TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
auto formUnsolved = [&]() {
// If we're supposed to generate constraints, do so.
if (flags.contains(TMF_GenerateConstraints)) {
auto *explictGenericArgs =
Constraint::create(*this, ConstraintKind::MaterializePackExpansion,
type1, type2, getConstraintLocator(locator));

addUnsolvedConstraint(explictGenericArgs);
return SolutionKind::Solved;
}

return SolutionKind::Unsolved;
};

type1 = simplifyType(type1);
if (type1->hasTypeVariable()) {
return formUnsolved();
}
if (auto patternType =
getPatternTypeOfSingleUnlabeledPackExpansionTuple(type1)) {
addConstraint(ConstraintKind::Equal, patternType, type2, locator);
return SolutionKind::Solved;
}

return SolutionKind::Error;
}

ConstraintSystem::SolutionKind
ConstraintSystem::simplifyExplicitGenericArgumentsConstraint(
Type type1, Type type2, TypeMatchOptions flags,
Expand Down Expand Up @@ -15179,6 +15230,10 @@ ConstraintSystem::addConstraintImpl(ConstraintKind kind, Type first,
return simplifyExplicitGenericArgumentsConstraint(
first, second, subflags, locator);

case ConstraintKind::MaterializePackExpansion:
return simplifyMaterializePackExpansionConstraint(first, second, subflags,
locator);

case ConstraintKind::ValueMember:
case ConstraintKind::UnresolvedValueMember:
case ConstraintKind::ValueWitness:
Expand Down Expand Up @@ -15758,6 +15813,11 @@ ConstraintSystem::simplifyConstraint(const Constraint &constraint) {
return simplifyExplicitGenericArgumentsConstraint(
constraint.getFirstType(), constraint.getSecondType(),
/*flags*/ llvm::None, constraint.getLocator());

case ConstraintKind::MaterializePackExpansion:
return simplifyMaterializePackExpansionConstraint(
constraint.getFirstType(), constraint.getSecondType(),
/*flags*/ llvm::None, constraint.getLocator());
}

llvm_unreachable("Unhandled ConstraintKind in switch.");
Expand Down
8 changes: 8 additions & 0 deletions lib/Sema/Constraint.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ Constraint::Constraint(ConstraintKind Kind, Type First, Type Second,
case ConstraintKind::ShapeOf:
case ConstraintKind::ExplicitGenericArguments:
case ConstraintKind::SameShape:
case ConstraintKind::MaterializePackExpansion:
assert(!First.isNull());
assert(!Second.isNull());
break;
Expand Down Expand Up @@ -173,6 +174,7 @@ Constraint::Constraint(ConstraintKind Kind, Type First, Type Second, Type Third,
case ConstraintKind::ShapeOf:
case ConstraintKind::ExplicitGenericArguments:
case ConstraintKind::SameShape:
case ConstraintKind::MaterializePackExpansion:
llvm_unreachable("Wrong constructor");

case ConstraintKind::KeyPath:
Expand Down Expand Up @@ -322,6 +324,7 @@ Constraint *Constraint::clone(ConstraintSystem &cs) const {
case ConstraintKind::ShapeOf:
case ConstraintKind::ExplicitGenericArguments:
case ConstraintKind::SameShape:
case ConstraintKind::MaterializePackExpansion:
return create(cs, getKind(), getFirstType(), getSecondType(), getLocator());

case ConstraintKind::ApplicableFunction:
Expand Down Expand Up @@ -579,6 +582,10 @@ void Constraint::print(llvm::raw_ostream &Out, SourceManager *sm,
Out << " explicit generic argument binding ";
break;

case ConstraintKind::MaterializePackExpansion:
Out << " materialize pack expansion ";
break;

case ConstraintKind::Disjunction:
llvm_unreachable("disjunction handled above");
case ConstraintKind::Conjunction:
Expand Down Expand Up @@ -748,6 +755,7 @@ gatherReferencedTypeVars(Constraint *constraint,
case ConstraintKind::ShapeOf:
case ConstraintKind::ExplicitGenericArguments:
case ConstraintKind::SameShape:
case ConstraintKind::MaterializePackExpansion:
constraint->getFirstType()->getTypeVariables(typeVars);
constraint->getSecondType()->getTypeVariables(typeVars);
break;
Expand Down
8 changes: 4 additions & 4 deletions lib/Sema/ConstraintSystem.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3614,9 +3614,8 @@ void ConstraintSystem::resolveOverload(ConstraintLocator *locator,
// In the future, _if_ the syntax allows for multiple expansions
// this code would have to be adjusted to project l-value from the
// base type just like TupleIndex does.
auto tuple = choice.getBaseType()->getRValueType()->castTo<TupleType>();
auto *expansion = tuple->getElementType(0)->castTo<PackExpansionType>();
adjustedRefType = expansion->getPatternType();
adjustedRefType =
getPatternTypeOfSingleUnlabeledPackExpansionTuple(choice.getBaseType());
refType = adjustedRefType;
break;
}
Expand Down Expand Up @@ -3873,7 +3872,8 @@ struct TypeSimplifier {
if (typeVar->getImpl().isPackExpansion() &&
!resolvedType->isEqual(typeVar) &&
!resolvedType->is<PackExpansionType>() &&
!resolvedType->is<PackType>()) {
!resolvedType->is<PackType>() &&
!resolvedType->is<PackArchetypeType>()) {
return resolvedType;
}
}
Expand Down
Loading