Skip to content

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

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 8 commits into from
Apr 16, 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
26 changes: 13 additions & 13 deletions include/swift/AST/Expr.h
Original file line number Diff line number Diff line change
Expand Up @@ -1449,23 +1449,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 @@ -1480,9 +1482,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 @@ -256,6 +256,7 @@ LANGUAGE_FEATURE(RawIdentifiers, 451, "Raw identifiers")
LANGUAGE_FEATURE(SendableCompletionHandlers, 463, "Objective-C completion handler parameters are imported as @Sendable")
LANGUAGE_FEATURE(AsyncExecutionBehaviorAttributes, 0, "@concurrent and nonisolated(nonsending)")
LANGUAGE_FEATURE(IsolatedConformances, 407, "Global-actor isolated conformances")
LANGUAGE_FEATURE(ValueGenericsNameLookup, 452, "Value generics appearing as static members for namelookup")

// Swift 6
UPCOMING_FEATURE(ConciseMagicFile, 274, 6)
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 @@ -470,6 +471,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 @@ -2739,6 +2739,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 @@ -3222,8 +3245,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 @@ -1135,6 +1149,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 @@ -6335,6 +6335,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
8 changes: 0 additions & 8 deletions stdlib/public/core/InlineArray.swift
Original file line number Diff line number Diff line change
Expand Up @@ -272,14 +272,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
26 changes: 26 additions & 0 deletions test/ModuleInterface/value_generics.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ public struct Slab<Element, let N: Int> {
public var count: Int {
N
}

public init() {}
}

// CHECK: public func usesGenericSlab<let N : Swift.Int>(_: ValueGeneric.Slab<Swift.Int, N>)
Expand All @@ -24,3 +26,27 @@ public func usesConcreteSlab(_: Slab<Int, 2>) {}

// CHECK: public func usesNegativeSlab(_: ValueGeneric.Slab<Swift.String, -10>)
public func usesNegativeSlab(_: Slab<String, -10>) {}

// CHECK: $ValueGenericsNameLookup
@inlinable
public func test() -> Int {
// CHECK: Slab<Int, 123>.N
Slab<Int, 123>.N
}

// CHECK: $ValueGenericsNameLookup
@inlinable
public func test2() -> Int {
// CHECK: type(of: Slab<Int, 123>()).N
type(of: Slab<Int, 123>()).N
}

// CHECK: $ValueGenericsNameLookup
@inlinable
public func test3() {
{
print(123)
print(123)
print(Slab<Int, 123>.N)
}()
}
Loading