Skip to content
Draft
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
4 changes: 4 additions & 0 deletions include/swift/AST/DiagnosticsSema.def
Original file line number Diff line number Diff line change
Expand Up @@ -8555,6 +8555,10 @@ NOTE(result_builder_infer_add_return, none,
NOTE(result_builder_infer_pick_specific, none,
"apply result builder %0 (inferred from %select{protocol|dynamic replacement of}1 %2)",
(Type, unsigned, DeclName))
ERROR(result_builder_generic_inference_failed, none,
"unable to infer generic arguments for result builder %0", (DeclAttribute))
ERROR(result_builder_generic_inference_ambiguous, none,
"generic arguments for result builder %0 are ambiguous", (DeclAttribute))
GROUPED_WARNING(result_builder_missing_limited_availability,
ResultBuilderMethods, none,
"result builder %0 does not implement 'buildLimitedAvailability'; "
Expand Down
5 changes: 5 additions & 0 deletions include/swift/AST/TypeCheckRequests.h
Original file line number Diff line number Diff line change
Expand Up @@ -4328,6 +4328,11 @@ enum class CustomAttrTypeKind {
/// Global actors are represented as custom type attributes. They don't
/// have any particularly interesting semantics.
GlobalActor,

/// Result builder types can omit their generic arguments, or use
/// placeholders, which are inferred when the result builder transform is
/// applied.
ResultBuilder,
};

void simple_display(llvm::raw_ostream &out, CustomAttrTypeKind value);
Expand Down
2 changes: 2 additions & 0 deletions lib/AST/Decl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,8 @@ Type Decl::getResolvedCustomAttrType(CustomAttr *attr) const {
kind = CustomAttrTypeKind::GlobalActor;
} else if (nominal->getAttrs().hasAttribute<PropertyWrapperAttr>()) {
kind = CustomAttrTypeKind::PropertyWrapper;
} else if (nominal->getAttrs().hasAttribute<ResultBuilderAttr>()) {
kind = CustomAttrTypeKind::ResultBuilder;
} else {
kind = CustomAttrTypeKind::NonGeneric;
}
Expand Down
4 changes: 4 additions & 0 deletions lib/AST/TypeCheckRequests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1969,6 +1969,10 @@ void swift::simple_display(llvm::raw_ostream &out, CustomAttrTypeKind value) {
case CustomAttrTypeKind::GlobalActor:
out << "global-actor";
return;

case CustomAttrTypeKind::ResultBuilder:
out << "result-builder";
return;
}

llvm_unreachable("bad kind");
Expand Down
5 changes: 4 additions & 1 deletion lib/Sema/CodeSynthesis.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,10 @@ static ParamDecl *createMemberwiseInitParameter(DeclContext *DC,

// Attach a result builder attribute if needed.
if (resultBuilderType) {
auto typeExpr = TypeExpr::createImplicit(resultBuilderType, ctx);
// The type of a custom attribute is a contextual type, while
// `getResultBuilderType` returns an interface type.
auto typeExpr = TypeExpr::createImplicit(
DC->mapTypeIntoEnvironment(resultBuilderType), ctx);
auto attr = CustomAttr::create(ctx, SourceLoc(), typeExpr, /*owner*/ arg,
/*implicit=*/true);
arg->addAttribute(attr);
Expand Down
12 changes: 11 additions & 1 deletion lib/Sema/TypeCheckRequestFunctions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -448,7 +448,7 @@ Type ResultBuilderTypeRequest::evaluate(Evaluator &evaluator,
auto &ctx = dc->getASTContext();
Type type = evaluateOrDefault(
evaluator,
CustomAttrTypeRequest{mutableAttr, dc, CustomAttrTypeKind::NonGeneric},
CustomAttrTypeRequest{mutableAttr, dc, CustomAttrTypeKind::ResultBuilder},
Type());
if (!type || type->hasError()) return Type();

Expand Down Expand Up @@ -484,6 +484,16 @@ Type ResultBuilderTypeRequest::evaluate(Evaluator &evaluator,
}
}

// Omitted generic arguments are inferred when resolving the attribute's type.
// If they couldn't be, because the declaration has no result type to infer
// them from, the attribute is invalid.
if (type->hasUnboundGenericType() || type->hasPlaceholder()) {
ctx.Diags.diagnose(attr->getLocation(),
diag::result_builder_generic_inference_failed, attr);
mutableAttr->setInvalid();
return Type();
}

return type->mapTypeOutOfEnvironment();
}

Expand Down
211 changes: 207 additions & 4 deletions lib/Sema/TypeCheckType.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,9 @@
#include "swift/Basic/Statistic.h"
#include "swift/ClangImporter/ClangImporter.h"
#include "swift/Parse/Lexer.h"
#include "swift/Sema/ConstraintSystem.h"
#include "swift/Sema/SILTypeResolutionContext.h"
#include "swift/Sema/TypeVariableType.h"
#include "swift/Subsystems.h"
#include "clang/AST/DeclTemplate.h"
#include "llvm/ADT/APInt.h"
Expand Down Expand Up @@ -8160,20 +8162,213 @@ void TypeChecker::checkExistentialTypes(
checker.checkRequirements(genericParams->getRequirements());
}

/// Returns the type produced by the result builder transform for the
/// declaration that the given result builder attribute is attached to.
static Type getResultBuilderAttrResultType(CustomAttr *attr) {
auto *owner = attr->getOwner().getAsDecl();
if (!owner)
return Type();

if (auto *func = dyn_cast<FuncDecl>(owner))
return func->getResultInterfaceType();

if (auto *subscript = dyn_cast<SubscriptDecl>(owner))
return subscript->getElementInterfaceType();

if (auto *var = dyn_cast<VarDecl>(owner)) {
auto type = var->getInterfaceType();
if (!type || type->hasError())
return Type();

// The result builder applies to the getter of a computed property.
if (!isa<ParamDecl>(var) && var->getParsedAccessor(AccessorKind::Get))
return type;

// Otherwise it applies to a closure: either the closure passed for a
// parameter, or the closure passed for a stored property to the memberwise
// initializer. A stored property that isn't of function type is
// initialized by a closure returning its type.
if (auto *fnType =
type->lookThroughAllOptionalTypes()->getAs<AnyFunctionType>())
return fnType->getResult();

return isa<ParamDecl>(var) ? Type() : type;
}

return Type();
}

/// Infers the generic arguments omitted from a result builder attribute, e.g.
/// `@Builder` or `@Builder<_>`, from the result type of the declaration it's
/// attached to.
static std::optional<Type>
inferResultBuilderGenericArguments(CustomAttr *attr, DeclContext *dc,
Type builderType) {
using namespace constraints;
auto &ctx = dc->getASTContext();

// If the generic arguments can't be inferred, the attribute is invalid.
auto loc = attr->getTypeExpr()->getLoc();
auto failed = [&]() -> Type {
ctx.Diags.diagnose(loc, diag::result_builder_generic_inference_failed,
attr);
return ErrorType::get(ctx);
};

auto *builderDecl = builderType->getAnyNominal();
if (!builderDecl)
return failed();

// Without a result type, the attribute is diagnosed separately by
// `ResultBuilderTypeRequest`.
auto resultType = getResultBuilderAttrResultType(attr);
if (!resultType)
return std::nullopt;
if (resultType->hasError())
return ErrorType::get(ctx);
resultType = dc->mapTypeIntoEnvironment(resultType);

auto supports = [&](Identifier name, ArrayRef<Identifier> labels = {}) {
return TypeChecker::typeSupportsBuilderOp(
builderDecl->getDeclaredInterfaceType(), builderDecl, name, labels);
};

// The generic arguments are inferred from the method that produces the final
// result of the transform, chosen in the same order of precedence that the
// transform uses: `buildFinalResult` if the builder has one (since it
// determines the type the transform ultimately produces), otherwise
// `buildPartialBlock(first:)` if the builder supports `buildPartialBlock`,
// otherwise `buildBlock`. The result types of the other methods aren't
// considered, even if they could produce the declaration's result type.
DeclNameRef methodName;
if (supports(ctx.Id_buildFinalResult)) {
methodName = DeclNameRef(ctx.Id_buildFinalResult);
} else if (supports(ctx.Id_buildPartialBlock, {ctx.Id_first}) &&
supports(ctx.Id_buildPartialBlock,
{ctx.Id_accumulated, ctx.Id_next})) {
methodName =
DeclNameRef(DeclName(ctx, ctx.Id_buildPartialBlock, {ctx.Id_first}));
} else if (supports(ctx.Id_buildBlock)) {
methodName = DeclNameRef(ctx.Id_buildBlock);
} else {
return failed();
}

// Infers the generic arguments with standard type inference, by type
// checking an unapplied reference to the method, with a function type
// returning the declaration's result type as its contextual type, like:
//
// let _: (_) -> Result = Builder.buildFinalResult
//
// `Builder` is the result builder type as written, including any unbound
// generic types or placeholders. All overloads of the method are candidates,
// and are resolved with the standard overload resolution rules.
//
// Returns the inferred builder type, an `ErrorType` if the reference is
// ambiguous (after diagnosing the ambiguity), or `std::nullopt` if the
// reference has no solution.
auto inferFromBuilderMethodReference =
[&](bool variadic) -> std::optional<Type> {
auto *typeExpr = TypeExpr::createImplicit(builderType, ctx);
auto *memberRef = new (ctx) UnresolvedDotExpr(
typeExpr, loc, methodName, DeclNameLoc(loc), /*implicit=*/true);
memberRef->setFunctionRefInfo(methodName.isCompoundName()
? FunctionRefInfo::unappliedCompoundName()
: FunctionRefInfo::unappliedBaseName());

ConstraintSystem cs(dc, ConstraintSystemOptions());
auto *expr = cs.generateConstraints(memberRef, dc);
if (!expr)
return std::nullopt;

// An opaque result type is opened like the type of an opaque variable
// (`let _: some Collection<String> = ...`), so its requirements can
// determine the generic arguments.
auto *locator = cs.getConstraintLocator(expr);
auto openedResultType = cs.openOpaqueType(
resultType, CTP_Initialization, locator, attr->getOwner().getAsDecl());
auto *paramType = cs.createTypeVariable(locator, TVO_CanBindToNoEscape);
AnyFunctionType::Param param(paramType, Identifier(),
ParameterTypeFlags().withVariadic(variadic));
auto contextualType = FunctionType::get(
{param}, /*yields=*/{}, openedResultType, FunctionType::ExtInfo());
cs.addConstraint(ConstraintKind::Conversion, cs.getType(expr),
contextualType, locator);

// If there's a single best solution, its generic arguments are used. If
// there are several, the generic arguments are ambiguous, and if there are
// none, they can't be inferred.
SmallVector<Solution, 4> solutions;
if (cs.solve(solutions) || solutions.empty())
return std::nullopt;

if (solutions.size() > 1) {
ctx.Diags.diagnose(loc, diag::result_builder_generic_inference_ambiguous,
attr);
// Note each candidate method chosen by one of the solutions.
llvm::SmallSetVector<ValueDecl *, 4> candidates;
for (const auto &solution : solutions) {
for (const auto &overload : solution.overloadChoices) {
auto *decl = overload.second.choice.getDeclOrNull();
if (decl && decl->getBaseName() == methodName.getBaseName())
candidates.insert(decl);
}
}
for (auto *decl : candidates)
decl->diagnose(diag::found_candidate);
return ErrorType::get(ctx);
}

auto inferred = solutions.front()
.simplifyType(cs.getType(typeExpr))
->getMetatypeInstanceType();
if (inferred->hasTypeVariable() || inferred->hasPlaceholder() ||
inferred->hasUnboundGenericType() || inferred->hasError())
return std::nullopt;

// The inferred type is used exactly as if its generic arguments had been
// written explicitly in the attribute. Like the type resolved for the
// attribute, it's a contextual type.
return inferred;
};

// `buildBlock` is usually variadic, so it's referenced as `(_...) -> Result`.
// It may instead be overloaded for specific numbers of components, so if that
// has no solution, it's referenced as `(_) -> Result`, which matches
// overloads taking a single component.
bool isBuildBlock = methodName.getBaseName() == ctx.Id_buildBlock;
auto inferred = inferFromBuilderMethodReference(/*variadic=*/isBuildBlock);
if (!inferred && isBuildBlock)
inferred = inferFromBuilderMethodReference(/*variadic=*/false);

if (!inferred)
return failed();

return *inferred;
}

Type CustomAttrTypeRequest::evaluate(Evaluator &eval, CustomAttr *attr,
DeclContext *dc,
CustomAttrTypeKind typeKind) const {
const TypeResolutionOptions options(TypeResolverContext::PatternBindingDecl);

OpenUnboundGenericTypeFn unboundTyOpener = nullptr;
// Property delegates allow their type to be an unbound generic.
HandlePlaceholderTypeReprFn placeholderHandler = nullptr;

// Property wrappers and result builders allow their type to be an unbound
// generic.
if (typeKind == CustomAttrTypeKind::PropertyWrapper) {
unboundTyOpener = TypeResolution::defaultUnboundTypeOpener;
} else if (typeKind == CustomAttrTypeKind::ResultBuilder) {
// Result builders also allow placeholders. Omitted generic arguments are
// inferred from the result type of the attached declaration below.
unboundTyOpener = TypeResolution::defaultUnboundTypeOpener;
placeholderHandler = PlaceholderType::get;
}

const auto type = TypeResolution::resolveContextualType(
attr->getTypeRepr(), dc, options, unboundTyOpener,
/*placeholderHandler*/ nullptr, /*packElementOpener*/ nullptr);
auto type = TypeResolution::resolveContextualType(
attr->getTypeRepr(), dc, options, unboundTyOpener, placeholderHandler,
/*packElementOpener*/ nullptr);

// We always require the type to resolve to a nominal type. If the type was
// not a nominal type, we should have already diagnosed an error via
Expand All @@ -8196,6 +8391,14 @@ Type CustomAttrTypeRequest::evaluate(Evaluator &eval, CustomAttr *attr,
return ErrorType::get(ctx);
}

// Infer any omitted generic arguments of a result builder from the result
// type of the attached declaration.
if (typeKind == CustomAttrTypeKind::ResultBuilder &&
(type->hasUnboundGenericType() || type->hasPlaceholder())) {
if (auto inferred = inferResultBuilderGenericArguments(attr, dc, type))
return *inferred;
}

return type;
}

Expand Down
Loading