Skip to content

[6.2] [NameLookup] Allow value generics to show up as static members #80855

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
May 7, 2025
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
9 changes: 7 additions & 2 deletions include/swift/AST/Decl.h
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,9 @@ struct OverloadSignature {
/// Whether this is a macro.
unsigned IsMacro : 1;

/// Whether this is a generic argument.
unsigned IsGenericArg : 1;

/// Whether this signature is part of a protocol extension.
unsigned InProtocolExtension : 1;

Expand All @@ -323,8 +326,10 @@ struct OverloadSignature {
OverloadSignature()
: UnaryOperator(UnaryOperatorKind::None), IsInstanceMember(false),
IsVariable(false), IsFunction(false), IsAsyncFunction(false),
IsDistributed(false), InProtocolExtension(false),
InExtensionOfGenericType(false), HasOpaqueReturnType(false) { }
IsDistributed(false), IsEnumElement(false), IsNominal(false),
IsTypeAlias(false), IsMacro(false), IsGenericArg(false),
InProtocolExtension(false), InExtensionOfGenericType(false),
HasOpaqueReturnType(false) { }
};

/// Determine whether two overload signatures conflict.
Expand Down
26 changes: 13 additions & 13 deletions include/swift/AST/Expr.h
Original file line number Diff line number Diff line change
Expand Up @@ -1454,23 +1454,25 @@ class TypeExpr : public Expr {
};

class TypeValueExpr : public Expr {
GenericTypeParamDecl *paramDecl;
DeclNameLoc loc;
TypeRepr *repr;
Type paramType;

/// Create a \c TypeValueExpr from a given generic value param decl.
TypeValueExpr(DeclNameLoc loc, GenericTypeParamDecl *paramDecl) :
Expr(ExprKind::TypeValue, /*implicit*/ false), paramDecl(paramDecl),
loc(loc), paramType(nullptr) {}
/// Create a \c TypeValueExpr from a given type representation.
TypeValueExpr(TypeRepr *repr) :
Expr(ExprKind::TypeValue, /*implicit*/ false), repr(repr),
paramType(nullptr) {}

public:
/// Create a \c TypeValueExpr for a given \c GenericTypeParamDecl.
/// Create a \c TypeValueExpr for a given \c TypeDecl.
///
/// The given location must be valid.
static TypeValueExpr *createForDecl(DeclNameLoc Loc, GenericTypeParamDecl *D);
static TypeValueExpr *createForDecl(DeclNameLoc loc, TypeDecl *d,
DeclContext *dc);

GenericTypeParamDecl *getParamDecl() const {
return paramDecl;
GenericTypeParamDecl *getParamDecl() const;

TypeRepr *getRepr() const {
return repr;
}

/// Retrieves the corresponding parameter type of the value referenced by this
Expand All @@ -1485,9 +1487,7 @@ class TypeValueExpr : public Expr {
this->paramType = paramType;
}

SourceRange getSourceRange() const {
return loc.getSourceRange();
}
SourceRange getSourceRange() const;

static bool classof(const Expr *E) {
return E->getKind() == ExprKind::TypeValue;
Expand Down
1 change: 1 addition & 0 deletions include/swift/Basic/Features.def
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,7 @@ LANGUAGE_FEATURE(SendableCompletionHandlers, 463, "Objective-C completion handle
LANGUAGE_FEATURE(IsolatedConformances, 470, "Global-actor isolated conformances")
LANGUAGE_FEATURE(AsyncExecutionBehaviorAttributes, 0, "@concurrent and nonisolated(nonsending)")
LANGUAGE_FEATURE(GeneralizedIsSameMetaTypeBuiltin, 465, "Builtin.is_same_metatype with support for noncopyable/nonescapable types")
LANGUAGE_FEATURE(ValueGenericsNameLookup, 452, "Value generics appearing as static members for namelookup")

// Swift 6
UPCOMING_FEATURE(ConciseMagicFile, 274, 6)
Expand Down
8 changes: 8 additions & 0 deletions lib/AST/Decl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3856,6 +3856,13 @@ bool swift::conflicting(ASTContext &ctx,
if (sig1.IsFunction != sig2.IsFunction)
return true;

// Gracefully handle the case where value generic arguments were introduced
// as a conflicting value with static variables of the same name.
if (sig1.IsGenericArg != sig2.IsGenericArg) {
*wouldConflictInSwift5 = true;
return true;
}

// Variables always conflict with non-variables with the same signature.
// (e.g variables with zero argument functions, variables with type
// declarations)
Expand Down Expand Up @@ -4034,6 +4041,7 @@ OverloadSignature ValueDecl::getOverloadSignature() const {
signature.IsNominal = isa<NominalTypeDecl>(this);
signature.IsTypeAlias = isa<TypeAliasDecl>(this);
signature.IsMacro = isa<MacroDecl>(this);
signature.IsGenericArg = isa<GenericTypeParamDecl>(this);
signature.HasOpaqueReturnType =
!signature.IsVariable && (bool)getOpaqueResultTypeDecl();

Expand Down
19 changes: 15 additions & 4 deletions lib/AST/Expr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2441,11 +2441,22 @@ bool Expr::isSelfExprOf(const AbstractFunctionDecl *AFD, bool sameBase) const {
return false;
}

TypeValueExpr *TypeValueExpr::createForDecl(DeclNameLoc loc,
GenericTypeParamDecl *paramDecl) {
auto &ctx = paramDecl->getASTContext();
TypeValueExpr *TypeValueExpr::createForDecl(DeclNameLoc loc, TypeDecl *decl,
DeclContext *dc) {
auto &ctx = decl->getASTContext();
ASSERT(loc.isValid());
return new (ctx) TypeValueExpr(loc, paramDecl);
auto repr = UnqualifiedIdentTypeRepr::create(ctx, loc, decl->createNameRef());
repr->setValue(decl, dc);
return new (ctx) TypeValueExpr(repr);
}

GenericTypeParamDecl *TypeValueExpr::getParamDecl() const {
auto declRefRepr = cast<DeclRefTypeRepr>(getRepr());
return cast<GenericTypeParamDecl>(declRefRepr->getBoundDecl());
}

SourceRange TypeValueExpr::getSourceRange() const {
return getRepr()->getSourceRange();
}

ExistentialArchetypeType *OpenExistentialExpr::getOpenedArchetype() const {
Expand Down
49 changes: 49 additions & 0 deletions lib/AST/FeatureSet.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

#include "FeatureSet.h"

#include "swift/AST/ASTWalker.h"
#include "swift/AST/Decl.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/GenericParamList.h"
Expand Down Expand Up @@ -489,6 +490,54 @@ static bool usesFeatureValueGenerics(Decl *decl) {
return false;
}

class UsesTypeValueExpr : public ASTWalker {
public:
bool used = false;

PreWalkResult<Expr *> walkToExprPre(Expr *expr) override {
if (isa<TypeValueExpr>(expr)) {
used = true;
return Action::Stop();
}

return Action::Continue(expr);
}
};

static bool usesFeatureValueGenericsNameLookup(Decl *decl) {
// Be conservative and mark any function that has a TypeValueExpr in its body
// as having used this feature. It's a little difficult to fine grain this
// check because the following:
//
// func a() -> Int {
// A<123>.n
// }
//
// Would appear to have the same expression as something like:
//
// extension A where n == 123 {
// func b() -> Int {
// n
// }
// }

auto fn = dyn_cast<AbstractFunctionDecl>(decl);

if (!fn)
return false;

auto body = fn->getMacroExpandedBody();

if (!body)
return false;

UsesTypeValueExpr utve;

body->walk(utve);

return utve.used;
}

static bool usesFeatureCoroutineAccessors(Decl *decl) {
auto accessorDeclUsesFeatureCoroutineAccessors = [](AccessorDecl *accessor) {
return requiresFeatureCoroutineAccessors(accessor->getAccessorKind());
Expand Down
12 changes: 12 additions & 0 deletions lib/AST/NameLookup.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2732,6 +2732,18 @@ QualifiedLookupRequest::evaluate(Evaluator &eval, const DeclContext *DC,
}
}

// Qualified name lookup can find generic value parameters.
auto gpList = current->getGenericParams();

// .. But not in type contexts (yet)
if (!(options & NL_OnlyTypes) && gpList && !member.isSpecial()) {
auto gp = gpList->lookUpGenericParam(member.getBaseIdentifier());

if (gp && gp->isValue()) {
decls.push_back(gp);
}
}

// If we're not looking at a protocol and we're not supposed to
// visit the protocols that this type conforms to, skip the next
// step.
Expand Down
37 changes: 36 additions & 1 deletion lib/Sema/CSApply.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1631,6 +1631,29 @@ namespace {
// Build a member reference.
auto memberRef = resolveConcreteDeclRef(member, memberLocator);

// If our member reference is a value generic, then the resulting
// expression is the type value one to access the underlying parameter's
// value.
//
// This can occur in code that does something like: 'type(of: x).a' where
// 'a' is the static value generic member.
if (auto gp = dyn_cast<GenericTypeParamDecl>(member)) {
if (gp->isValue()) {
auto refType = adjustedOpenedType;
auto ref = TypeValueExpr::createForDecl(memberLoc, gp, dc);
cs.setType(ref, refType);

auto gpTy = gp->getDeclaredInterfaceType();
auto subs = baseTy->getContextSubstitutionMap();
ref->setParamType(gpTy.subst(subs));

auto result = new (ctx) DotSyntaxBaseIgnoredExpr(base, dotLoc, ref,
refType);
cs.setType(result, refType);
return result;
}
}

// If we're referring to a member type, it's just a type
// reference.
if (auto *TD = dyn_cast<TypeDecl>(member)) {
Expand Down Expand Up @@ -3223,8 +3246,20 @@ namespace {

Expr *visitTypeValueExpr(TypeValueExpr *expr) {
auto toType = simplifyType(cs.getType(expr));
assert(toType->isEqual(expr->getParamDecl()->getValueType()));
ASSERT(toType->isEqual(expr->getParamDecl()->getValueType()));
cs.setType(expr, toType);

auto declRefRepr = cast<DeclRefTypeRepr>(expr->getRepr());
auto resolvedTy =
TypeResolution::resolveContextualType(declRefRepr, cs.DC,
TypeResolverContext::InExpression,
nullptr, nullptr, nullptr);

if (!resolvedTy || resolvedTy->hasError())
return nullptr;

expr->setParamType(resolvedTy);

return expr;
}

Expand Down
3 changes: 0 additions & 3 deletions lib/Sema/CSGen.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1723,9 +1723,6 @@ namespace {
}

Type visitTypeValueExpr(TypeValueExpr *E) {
auto ty = E->getParamDecl()->getDeclaredInterfaceType();
auto paramType = CS.DC->mapTypeIntoContext(ty);
E->setParamType(paramType);
return E->getParamDecl()->getValueType();
}

Expand Down
5 changes: 2 additions & 3 deletions lib/Sema/PreCheckTarget.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -817,8 +817,7 @@ Expr *TypeChecker::resolveDeclRefExpr(UnresolvedDeclRefExpr *UDRE,
: D->getInterfaceType());
} else {
if (makeTypeValue) {
return TypeValueExpr::createForDecl(UDRE->getNameLoc(),
cast<GenericTypeParamDecl>(D));
return TypeValueExpr::createForDecl(UDRE->getNameLoc(), D, LookupDC);
} else {
return TypeExpr::createForDecl(UDRE->getNameLoc(), D, LookupDC);
}
Expand Down Expand Up @@ -1853,7 +1852,7 @@ TypeExpr *PreCheckTarget::simplifyUnresolvedSpecializeExpr(
UnresolvedSpecializeExpr *us) {
// If this is a reference type a specialized type, form a TypeExpr.
// The base should be a TypeExpr that we already resolved.
if (auto *te = dyn_cast<TypeExpr>(us->getSubExpr())) {
if (auto *te = dyn_cast_or_null<TypeExpr>(us->getSubExpr())) {
if (auto *declRefTR =
dyn_cast_or_null<DeclRefTypeRepr>(te->getTypeRepr())) {
return TypeExpr::createForSpecializedDecl(
Expand Down
15 changes: 15 additions & 0 deletions lib/Sema/TypeCheckDeclPrimary.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -728,6 +728,20 @@ CheckRedeclarationRequest::evaluate(Evaluator &eval, ValueDecl *current,
auto found = nominal->lookupDirect(current->getBaseName(), SourceLoc(),
flags);
otherDefinitions.append(found.begin(), found.end());

// Look into the generics of the type. Value generic parameters can appear
// as static members of the type.
if (auto genericDC = static_cast<Decl *>(nominal)->getAsGenericContext()) {
auto gpList = genericDC->getGenericParams();

if (gpList && !current->getBaseName().isSpecial()) {
auto gp = gpList->lookUpGenericParam(current->getBaseIdentifier());

if (gp && gp->isValue()) {
otherDefinitions.push_back(gp);
}
}
}
}
} else if (currentDC->isLocalContext()) {
if (!current->isImplicit()) {
Expand Down Expand Up @@ -1136,6 +1150,7 @@ CheckRedeclarationRequest::evaluate(Evaluator &eval, ValueDecl *current,
break;
}
}

return std::make_tuple<>();
}

Expand Down
12 changes: 12 additions & 0 deletions lib/Sema/TypeCheckType.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6341,6 +6341,18 @@ Type TypeChecker::substMemberTypeWithBase(TypeDecl *member,
resultType = TypeAliasType::get(aliasDecl, sugaredBaseTy, {}, resultType);
}

// However, if overload resolution finds a value generic decl from name
// lookup, replace the returned member type to be the underlying value type
// of the generic.
//
// This can occur in code that does something like: 'type(of: x).a' where
// 'a' is the static value generic member.
if (auto gp = dyn_cast<GenericTypeParamDecl>(member)) {
if (gp->isValue()) {
resultType = gp->getValueType();
}
}

return resultType;
}

Expand Down
7 changes: 7 additions & 0 deletions lib/Sema/TypeOfReference.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1557,6 +1557,13 @@ DeclReferenceType ConstraintSystem::getTypeOfMemberReference(
// Wrap it in a metatype.
memberTy = MetatypeType::get(memberTy);

// If this is a value generic, undo the wrapping. 'substMemberTypeWithBase'
// returns the underlying value type of the value generic (e.g. 'Int').
if (isa<GenericTypeParamDecl>(value) &&
cast<GenericTypeParamDecl>(value)->isValue()) {
memberTy = memberTy->castTo<MetatypeType>()->getInstanceType();
}

auto openedType = FunctionType::get({baseObjParam}, memberTy);
return { openedType, openedType, memberTy, memberTy, Type() };
}
Expand Down
12 changes: 4 additions & 8 deletions stdlib/public/core/InlineArray.swift
Original file line number Diff line number Diff line change
Expand Up @@ -247,11 +247,15 @@ extension InlineArray where Element: Copyable {
@available(SwiftStdlib 6.2, *)
@_alwaysEmitIntoClient
public init(repeating value: Element) {
#if $ValueGenericsNameLookup
self = Builtin.emplace {
let buffer = unsafe Self._initializationBuffer(start: $0)

unsafe buffer.initialize(repeating: value)
}
#else
fatalError()
#endif
}
}

Expand All @@ -273,14 +277,6 @@ extension InlineArray where Element: ~Copyable {
@available(SwiftStdlib 6.2, *)
public typealias Index = Int

// FIXME: Remove when SE-0452 "Integer Generic Parameters" is implemented.
@available(SwiftStdlib 6.2, *)
@_alwaysEmitIntoClient
@_transparent
public static var count: Int {
count
}

/// The number of elements in the array.
///
/// - Complexity: O(1)
Expand Down
Loading