Skip to content

AST/Parse: Parse custom availability domain specs in if #available(...) #79628

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
Feb 28, 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
3 changes: 3 additions & 0 deletions include/swift/AST/AvailabilityDomain.h
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,9 @@ class AvailabilityDomain final {
/// version ranges.
bool isVersioned() const;

/// Returns true if the domain supports `#available`/`#unavailable` queries.
bool supportsQueries() const;

/// Returns true if this domain is considered active in the current
/// compilation context.
bool isActive(const ASTContext &ctx) const;
Expand Down
25 changes: 11 additions & 14 deletions include/swift/AST/DiagnosticsSema.def
Original file line number Diff line number Diff line change
Expand Up @@ -6754,8 +6754,10 @@ NOTE(type_eraser_init_spi,none,
//------------------------------------------------------------------------------

ERROR(availability_must_occur_alone, none,
"'%0' version-availability must be specified alone", (StringRef))

"%0 %select{|version }1availability must be specified alone",
(StringRef, bool))
ERROR(availability_unexpected_version, none,
"unexpected version number for %0", (StringRef))
WARNING(availability_unrecognized_platform_name,
PointsToFirstBadToken, "unrecognized platform name %0", (Identifier))
WARNING(availability_suggest_platform_name,
Expand All @@ -6773,11 +6775,8 @@ WARNING(attr_availability_expected_version_spec, none,
"expected 'introduced', 'deprecated', or 'obsoleted' in '%0' attribute "
"for platform '%1'", (StringRef, StringRef))
ERROR(attr_availability_requires_custom_availability, none,
"%0 requires -enable-experimental-feature CustomAvailability",
(Identifier))
WARNING(attr_availability_unexpected_version,none,
"unexpected version number in '%0' attribute for '%1'",
(const DeclAttribute, StringRef))
"%0 requires '-enable-experimental-feature CustomAvailability'",
(StringRef))

ERROR(availability_decl_unavailable, none,
"%0 is unavailable%select{ in %2|}1%select{|: %3}3",
Expand Down Expand Up @@ -7002,14 +7001,12 @@ ERROR(conformance_availability_only_version_newer, none,
// MARK: if #available(...)
//------------------------------------------------------------------------------

ERROR(availability_query_swift_not_allowed, none,
"Swift language version checks not allowed in %0(...)", (StringRef))

ERROR(availability_query_package_description_not_allowed, none,
"PackageDescription version checks not allowed in %0(...)", (StringRef))
ERROR(availability_query_not_allowed, none,
"%0 %select{|version }1checks not allowed in %2(...)",
(StringRef, bool, StringRef))

ERROR(availability_query_repeated_platform, none,
"version for '%0' already specified", (StringRef))
ERROR(availability_query_already_specified, none,
"%select{|version for }0'%1' already specified", (bool, StringRef))

ERROR(availability_query_wildcard_required, none,
"must handle potential future platforms with '*'", ())
Expand Down
16 changes: 12 additions & 4 deletions lib/AST/Availability.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -835,8 +835,9 @@ SemanticAvailableAttrRequest::evaluate(swift::Evaluator &evaluator,
versionSourceRange = semanticAttr.getObsoletedSourceRange();

diags
.diagnose(attrLoc, diag::attr_availability_unexpected_version, attr,
domainName)
.diagnose(attrLoc, diag::availability_unexpected_version,
domain->getNameForDiagnostics())
.limitBehaviorIf(domain->isUniversal(), DiagnosticBehavior::Warning)
.highlight(versionSourceRange);
return std::nullopt;
}
Expand All @@ -862,11 +863,18 @@ SemanticAvailableAttrRequest::evaluate(swift::Evaluator &evaluator,
case AvailableAttr::Kind::Default:
break;
}
}

if (!hasVersionSpec) {
diags.diagnose(attrLoc, diag::attr_availability_expected_version_spec,
if (!hasVersionSpec && domain->isVersioned()) {
switch (attr->getKind()) {
case AvailableAttr::Kind::Default:
diags.diagnose(domainLoc, diag::attr_availability_expected_version_spec,
attrName, domainName);
return std::nullopt;
case AvailableAttr::Kind::Deprecated:
case AvailableAttr::Kind::Unavailable:
case AvailableAttr::Kind::NoAsync:
break;
}
}

Expand Down
17 changes: 15 additions & 2 deletions lib/AST/AvailabilityDomain.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,19 @@ bool AvailabilityDomain::isVersioned() const {
}
}

bool AvailabilityDomain::supportsQueries() const {
switch (getKind()) {
case Kind::Universal:
case Kind::Embedded:
case Kind::SwiftLanguage:
case Kind::PackageDescription:
return false;
case Kind::Platform:
case Kind::Custom:
return true;
}
}

bool AvailabilityDomain::isActive(const ASTContext &ctx) const {
switch (getKind()) {
case Kind::Universal:
Expand All @@ -94,7 +107,7 @@ bool AvailabilityDomain::isActive(const ASTContext &ctx) const {
llvm::StringRef AvailabilityDomain::getNameForDiagnostics() const {
switch (getKind()) {
case Kind::Universal:
return "";
return "*";
case Kind::SwiftLanguage:
return "Swift";
case Kind::PackageDescription:
Expand Down Expand Up @@ -247,7 +260,7 @@ AvailabilityDomainOrIdentifier::lookUpInDeclContext(
!ctx.LangOpts.hasFeature(Feature::CustomAvailability) &&
!declContext->isInSwiftinterface()) {
diags.diagnose(loc, diag::attr_availability_requires_custom_availability,
identifier);
domain->getNameForDiagnostics());
return std::nullopt;
}

Expand Down
20 changes: 15 additions & 5 deletions lib/AST/AvailabilitySpec.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -29,22 +29,32 @@ AvailabilitySpec *AvailabilitySpec::createWildcard(ASTContext &ctx,
/*VersionStartLoc=*/{});
}

static SourceRange getSpecSourceRange(SourceLoc domainLoc,
SourceRange versionRange) {
if (domainLoc.isInvalid())
return SourceRange();

if (versionRange.isValid())
return SourceRange(domainLoc, versionRange.End);

return SourceRange(domainLoc);
}

AvailabilitySpec *AvailabilitySpec::createForDomain(ASTContext &ctx,
AvailabilityDomain domain,
SourceLoc loc,
llvm::VersionTuple version,
SourceRange versionRange) {
DEBUG_ASSERT(!version.empty());
return new (ctx) AvailabilitySpec(domain, SourceRange(loc, versionRange.End),
version, versionRange.Start);
return new (ctx)
AvailabilitySpec(domain, getSpecSourceRange(loc, versionRange), version,
versionRange.Start);
}

AvailabilitySpec *AvailabilitySpec::createForDomainIdentifier(
ASTContext &ctx, Identifier domainIdentifier, SourceLoc loc,
llvm::VersionTuple version, SourceRange versionRange) {
DEBUG_ASSERT(!version.empty());
return new (ctx)
AvailabilitySpec(domainIdentifier, SourceRange(loc, versionRange.End),
AvailabilitySpec(domainIdentifier, getSpecSourceRange(loc, versionRange),
version, versionRange.Start);
}

Expand Down
1 change: 1 addition & 0 deletions lib/ASTGen/Sources/ASTGen/Availability.swift
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,7 @@ extension ASTGenVisitor {
var result: [BridgedAvailabilitySpec] = []

func handle(domainNode: TokenSyntax, versionNode: VersionTupleSyntax?) {
// FIXME: [availability] Add support for custom domains
let nameLoc = self.generateSourceLoc(domainNode)
let version = self.generate(versionTuple: versionNode)
let versionRange = self.generateSourceRange(versionNode)
Expand Down
8 changes: 5 additions & 3 deletions lib/Parse/ParseExpr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3715,9 +3715,11 @@ ParserResult<AvailabilitySpec> Parser::parseAvailabilitySpec() {
llvm::VersionTuple Version;
SourceRange VersionRange;

if (parseVersionTuple(Version, VersionRange,
diag::avail_query_expected_version_number)) {
return nullptr;
if (Tok.isAny(tok::integer_literal, tok::floating_literal)) {
if (parseVersionTuple(Version, VersionRange,
diag::avail_query_expected_version_number)) {
return nullptr;
}
}

return makeParserResult(AvailabilitySpec::createForDomainIdentifier(
Expand Down
2 changes: 1 addition & 1 deletion lib/Parse/ParseStmt.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1481,7 +1481,7 @@ Parser::parseAvailabilitySpecList(SmallVectorImpl<AvailabilitySpec *> &Specs,
diag::avail_query_meant_introduced)
.fixItInsert(PlatformNameEndLoc, ", introduced:");
}

consumeToken();
Status.setIsParseError();
break;
}
Expand Down
47 changes: 35 additions & 12 deletions lib/Sema/MiscDiagnostics.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
#include "swift/AST/ASTWalker.h"
#include "swift/AST/AvailabilitySpec.h"
#include "swift/AST/ConformanceLookup.h"
#include "swift/AST/DiagnosticsParse.h"
#include "swift/AST/DiagnosticsSema.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/Expr.h"
Expand Down Expand Up @@ -5130,6 +5131,8 @@ static bool diagnoseAvailabilityCondition(PoundAvailableInfo *info,
StringRef queryName =
info->isUnavailability() ? "#unavailable" : "#available";

bool hasValidSpecs = false;
bool allValidSpecsArePlatform = true;
std::optional<SourceLoc> wildcardLoc;
llvm::SmallSet<AvailabilityDomain, 8> seenDomains;
for (auto spec : info->getSemanticAvailabilitySpecs(DC)) {
Expand All @@ -5140,24 +5143,44 @@ static bool diagnoseAvailabilityCondition(PoundAvailableInfo *info,
}

auto domain = spec.getDomain();
auto loc = parsedSpec->getStartLoc();
bool hasVersion = !spec.getVersion().empty();

if (!domain.isPlatform()) {
diags.diagnose(
parsedSpec->getStartLoc(),
domain.isSwiftLanguage()
? diag::availability_query_swift_not_allowed
: diag::availability_query_package_description_not_allowed,
queryName);
if (!domain.supportsQueries()) {
diags.diagnose(loc, diag::availability_query_not_allowed,
domain.getNameForDiagnostics(), hasVersion, queryName);
return true;
}

// Diagnose duplicate platforms.
if (!domain.isPlatform() && info->getQueries().size() > 1) {
diags.diagnose(loc, diag::availability_must_occur_alone,
domain.getNameForDiagnostics(), hasVersion);
return true;
}

if (domain.isVersioned()) {
if (!hasVersion) {
diags.diagnose(loc, diag::avail_query_expected_version_number);
return true;
}
} else if (hasVersion) {
diags
.diagnose(loc, diag::availability_unexpected_version,
domain.getNameForDiagnostics())
.highlight(parsedSpec->getVersionSrcRange());
return true;
}

// Diagnose duplicate domains.
if (!seenDomains.insert(domain).second) {
diags.diagnose(parsedSpec->getStartLoc(),
diag::availability_query_repeated_platform,
domain.getNameForAttributePrinting());
diags.diagnose(loc, diag::availability_query_already_specified,
domain.isVersioned(), domain.getNameForDiagnostics());
return true;
}

hasValidSpecs = true;
if (!domain.isPlatform())
allValidSpecsArePlatform = false;
}

if (info->isUnavailability()) {
Expand All @@ -5167,7 +5190,7 @@ static bool diagnoseAvailabilityCondition(PoundAvailableInfo *info,
diag::unavailability_query_wildcard_not_required)
.fixItRemove(*wildcardLoc);
}
} else if (!wildcardLoc) {
} else if (!wildcardLoc && hasValidSpecs && allValidSpecsArePlatform) {
if (info->getQueries().size() > 0) {
auto insertLoc = info->getQueries().back()->getSourceRange().End;
diags.diagnose(insertLoc, diag::availability_query_wildcard_required)
Expand Down
18 changes: 11 additions & 7 deletions lib/Sema/TypeCheckAttr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4979,8 +4979,9 @@ void AttributeChecker::checkAvailableAttrs(ArrayRef<AvailableAttr *> attrs) {
llvm::SmallSet<AvailabilityDomain, 8> seenDomains;

SourceLoc groupEndLoc;
bool requiresWildcard = false;
bool foundWildcard = false;
bool hasValidSpecs = false;
bool allValidSpecsArePlatform = true;
int groupAttrCount = 0;
for (auto *groupedAttr = groupHead; groupedAttr != nullptr;
groupedAttr = groupedAttr->getNextGroupedAvailableAttr()) {
Expand All @@ -4999,28 +5000,31 @@ void AttributeChecker::checkAvailableAttrs(ArrayRef<AvailableAttr *> attrs) {
continue;

auto domain = attr->getDomain();
if (domain.isPlatform())
requiresWildcard = true;

if (groupAttrCount > 1 || !groupedAttr->isGroupTerminator() ||
foundWildcard) {
// Only platform availability is allowed to be written groups with more
// than one member.
if (!domain.isPlatform()) {
diagnose(loc, diag::availability_must_occur_alone,
domain.getNameForAttributePrinting());
domain.getNameForDiagnostics(), domain.isVersioned());
continue;
}
}

// Diagnose duplicate platforms.
if (!seenDomains.insert(domain).second) {
diagnose(loc, diag::availability_query_repeated_platform,
domain.getNameForAttributePrinting());
diagnose(loc, diag::availability_query_already_specified,
domain.isVersioned(), domain.getNameForAttributePrinting());
continue;
}

hasValidSpecs = true;
if (!domain.isPlatform())
allValidSpecsArePlatform = false;
}

if (requiresWildcard && !foundWildcard) {
if (!foundWildcard && hasValidSpecs && allValidSpecsArePlatform) {
diagnose(groupEndLoc, diag::availability_query_wildcard_required)
.fixItInsert(groupEndLoc, ", *");
}
Expand Down
11 changes: 6 additions & 5 deletions test/Parse/availability_query.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ if #available( { // expected-error {{expected platform name}} expected-error {{e
if #available() { // expected-error {{expected platform name}}
}

if #available(OSX { // expected-error {{expected version number}} expected-error {{expected ')'}} expected-note {{to match this opening '('}}
if #available(OSX { // expected-error {{expected ')'}} expected-note {{to match this opening '('}}
}

if #available(OSX) { // expected-error {{expected version number}}
Expand All @@ -46,8 +46,7 @@ if #available(OSX 51 { // expected-error {{expected ')'}} expected-note {{to mat
}

if #available(iDishwasherOS 51) { // expected-warning {{unrecognized platform name 'iDishwasherOS'}}
// expected-error@-1 {{must handle potential future platforms with '*'}}
// expected-error@-2 {{condition required for target platform}}
// expected-error@-1 {{condition required for target platform}}
}

if #available(iDishwasherOS 51, *) { // expected-warning {{unrecognized platform name 'iDishwasherOS'}}
Expand Down Expand Up @@ -75,7 +74,9 @@ if #available(OSX 51, iOS 8.0) { } // expected-error {{must handle potential fu
if #available(iOS 8.0, *) {
}

if #available(iOSApplicationExtension, unavailable) { // expected-error 2{{expected version number}}
if #available(iOSApplicationExtension, unavailable) { // expected-error {{'unavailable' can't be combined with shorthand specification 'iOSApplicationExtension'}}
// expected-error@-1 {{condition required for target platform}}
// expected-note@-2 {{did you mean to specify an introduction version?}}
}

// Want to make sure we can parse this. Perhaps we should not let this validate, though.
Expand All @@ -96,7 +97,7 @@ if #available(OSX 51, { // expected-error {{expected platform name}} // expected
if #available(OSX 51,) { // expected-error {{expected platform name}}
}

if #available(OSX 51, iOS { // expected-error {{expected version number}} // expected-error {{expected ')'}} expected-note {{to match this opening '('}}
if #available(OSX 51, iOS { // expected-error {{expected ')'}} expected-note {{to match this opening '('}}
}

if #available(OSX 51, iOS 8.0, iDishwasherOS 51) { // expected-warning {{unrecognized platform name 'iDishwasherOS'}}
Expand Down
7 changes: 4 additions & 3 deletions test/Parse/availability_query_unavailability.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ if #unavailable( { // expected-error {{expected platform name}} expected-error {
if #unavailable() { // expected-error {{expected platform name}}
}

if #unavailable(OSX { // expected-error {{expected version number}} expected-error {{expected ')'}} expected-note {{to match this opening '('}}
if #unavailable(OSX { // expected-error {{expected ')'}} expected-note {{to match this opening '('}}
}

if #unavailable(OSX) { // expected-error {{expected version number}}
Expand Down Expand Up @@ -62,7 +62,8 @@ if #unavailable(OSX 51, iOS 8.0, *) { } // expected-error {{platform wildcard '
if #unavailable(iOS 8.0) {
}

if #unavailable(iOSApplicationExtension, unavailable) { // expected-error 2{{expected version number}}
if #unavailable(iOSApplicationExtension, unavailable) { // expected-error {{'unavailable' can't be combined with shorthand specification 'iOSApplicationExtension'}}
// expected-note@-1 {{did you mean to specify an introduction version?}}
}

// Should this be a valid spelling since `#unvailable(*)` cannot be written?
Expand All @@ -80,7 +81,7 @@ if #unavailable(OSX 51, iOS 8.0) {
if #unavailable(OSX 51, { // expected-error {{expected platform name}} // expected-error {{expected ')'}} expected-note {{to match this opening '('}}
}

if #unavailable(OSX 51, iOS { // expected-error {{expected version number}} // expected-error {{expected ')'}} expected-note {{to match this opening '('}}
if #unavailable(OSX 51, iOS { // expected-error {{expected ')'}} expected-note {{to match this opening '('}}
}

if #unavailable(OSX 51, iOS 8.0, iDishwasherOS 51) { // expected-warning {{unrecognized platform name 'iDishwasherOS'}}
Expand Down
Loading