Skip to content

[Sema] Require explicit availability on public modules and customizable diagnostics level #61105

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 5 commits into from
Sep 15, 2022
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
5 changes: 5 additions & 0 deletions include/swift/AST/DiagnosticsFrontend.def
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@ ERROR(error_unknown_library_level, none,
"unknown library level '%0', "
"expected one of 'api', 'spi' or 'other'", (StringRef))

ERROR(error_unknown_require_explicit_availability, none,
"unknown argument '%0', passed to -require-explicit-availability, "
"expected 'error', 'warn' or 'ignore'",
(StringRef))

ERROR(error_unsupported_opt_for_target, none,
"unsupported option '%0' for target '%1'", (StringRef, StringRef))

Expand Down
6 changes: 3 additions & 3 deletions include/swift/AST/DiagnosticsSema.def
Original file line number Diff line number Diff line change
Expand Up @@ -5749,9 +5749,9 @@ ERROR(availability_protocol_requires_version,
NOTE(availability_protocol_requirement_here, none,
"protocol requirement here", ())

WARNING(public_decl_needs_availability, none,
"public declarations should have an availability attribute when building "
"with -require-explicit-availability", ())
ERROR(public_decl_needs_availability, none,
"public declarations should have an availability attribute "
"with an introduction version", ())

ERROR(attr_requires_decl_availability_for_platform,none,
"'%0' requires that %1 have explicit availability for %2",
Expand Down
5 changes: 3 additions & 2 deletions include/swift/Basic/LangOptions.h
Original file line number Diff line number Diff line change
Expand Up @@ -193,8 +193,9 @@ namespace swift {
/// Enable 'availability' restrictions for App Extensions.
bool EnableAppExtensionRestrictions = false;

/// Require public declarations to declare an introduction OS version.
bool RequireExplicitAvailability = false;
/// Diagnostic level to report when a public declarations doesn't declare
/// an introduction OS version.
Optional<DiagnosticBehavior> RequireExplicitAvailability = None;

/// Introduction platform and version to suggest as fix-it
/// when using RequireExplicitAvailability.
Expand Down
8 changes: 7 additions & 1 deletion include/swift/Option/Options.td
Original file line number Diff line number Diff line change
Expand Up @@ -411,7 +411,13 @@ def enable_library_evolution : Flag<["-"], "enable-library-evolution">,

def require_explicit_availability : Flag<["-"], "require-explicit-availability">,
Flags<[FrontendOption, NoInteractiveOption]>,
HelpText<"Require explicit availability on public declarations">;
HelpText<"Warn on public declarations without an availability attribute">;

def require_explicit_availability_EQ : Joined<["-"], "require-explicit-availability=">,
Copy link
Contributor

Choose a reason for hiding this comment

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

Do you think it would make sense to name this -require-explicit-api-availability= to help distinguish if we want to also add a similar -require-explicit-spi-availability= flag in the future?

I suppose an alternative design could be to add a -require-explicit-availability-for-spi-groups= flag that takes SPI group names that should be diagnosed at the same level as API, rather than having it be all or nothing for SPI.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I was considering renaming the flag to -require-availability, just to make it shorter even if a bit less descriptive.

Interesting idea for SPI, in most cases SPI doesn't require any availability so I don't think we'd need the "all SPI" version, but for specific SPI groups it could be useful and a good practice to apply. Users would have to learn to mark their features as SPI first before upgrading them to API instead of the other way around though.

MetaVarName<"<error,warn,ignore>">,
Flags<[FrontendOption, NoInteractiveOption]>,
HelpText<"Set diagnostic level to report public declarations without an availability attribute">;

def require_explicit_availability_target : Separate<["-"], "require-explicit-availability-target">,
Flags<[FrontendOption, NoInteractiveOption]>,
HelpText<"Suggest fix-its adding @available(<target>, *) to public declarations without availability">,
Expand Down
1 change: 1 addition & 0 deletions lib/Driver/ToolChains.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,7 @@ void ToolChain::addCommonFrontendArgs(const OutputInfo &OI,
inputArgs.AddLastArg(arguments, options::OPT_enable_library_evolution);
inputArgs.AddLastArg(arguments, options::OPT_require_explicit_availability);
inputArgs.AddLastArg(arguments, options::OPT_require_explicit_availability_target);
inputArgs.AddLastArg(arguments, options::OPT_require_explicit_availability_EQ);
inputArgs.AddLastArg(arguments, options::OPT_require_explicit_sendable);
inputArgs.AddLastArg(arguments, options::OPT_check_api_availability_only);
inputArgs.AddLastArg(arguments, options::OPT_enable_testing);
Expand Down
30 changes: 23 additions & 7 deletions lib/Frontend/CompilerInvocation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -587,13 +587,6 @@ static bool ParseLangArgs(LangOptions &Opts, ArgList &Args,
if (Args.getLastArg(OPT_debug_cycles))
Opts.DebugDumpCycles = true;

if (Args.getLastArg(OPT_require_explicit_availability, OPT_require_explicit_availability_target)) {
Opts.RequireExplicitAvailability = true;
if (const Arg *A = Args.getLastArg(OPT_require_explicit_availability_target)) {
Opts.RequireExplicitAvailabilityTarget = A->getValue();
}
}

Opts.RequireExplicitSendable |= Args.hasArg(OPT_require_explicit_sendable);
for (const Arg *A : Args.filtered(OPT_define_availability)) {
Opts.AvailabilityMacros.push_back(A->getValue());
Expand Down Expand Up @@ -721,6 +714,29 @@ static bool ParseLangArgs(LangOptions &Opts, ArgList &Args,
}
}

if (const Arg *A = Args.getLastArg(OPT_require_explicit_availability_EQ)) {
StringRef diagLevel = A->getValue();
if (diagLevel == "warn") {
Opts.RequireExplicitAvailability = DiagnosticBehavior::Warning;
} else if (diagLevel == "error") {
Opts.RequireExplicitAvailability = DiagnosticBehavior::Error;
} else if (diagLevel == "ignore") {
Opts.RequireExplicitAvailability = None;
} else {
Diags.diagnose(SourceLoc(),
diag::error_unknown_require_explicit_availability,
diagLevel);
}
} else if (Args.getLastArg(OPT_require_explicit_availability,
OPT_require_explicit_availability_target) ||
Opts.LibraryLevel == LibraryLevel::API) {
Opts.RequireExplicitAvailability = DiagnosticBehavior::Warning;
}

if (const Arg *A = Args.getLastArg(OPT_require_explicit_availability_target)) {
Opts.RequireExplicitAvailabilityTarget = A->getValue();
}

Opts.EnableSPIOnlyImports = Args.hasArg(OPT_experimental_spi_only_imports);

if (Opts.EnableSwift3ObjCInference) {
Expand Down
4 changes: 3 additions & 1 deletion lib/Sema/TypeCheckAvailability.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4279,7 +4279,8 @@ static bool declNeedsExplicitAvailability(const Decl *decl) {
void swift::checkExplicitAvailability(Decl *decl) {
// Skip if the command line option was not set and
// accessors as we check the pattern binding decl instead.
if (!decl->getASTContext().LangOpts.RequireExplicitAvailability ||
auto DiagLevel = decl->getASTContext().LangOpts.RequireExplicitAvailability;
if (!DiagLevel ||
isa<AccessorDecl>(decl))
return;

Expand Down Expand Up @@ -4323,6 +4324,7 @@ void swift::checkExplicitAvailability(Decl *decl) {

if (declNeedsExplicitAvailability(decl)) {
auto diag = decl->diagnose(diag::public_decl_needs_availability);
diag.limitBehavior(*DiagLevel);

auto suggestPlatform =
decl->getASTContext().LangOpts.RequireExplicitAvailabilityTarget;
Expand Down
3 changes: 2 additions & 1 deletion stdlib/cmake/modules/SwiftSource.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -483,7 +483,8 @@ function(_compile_swift_files
# The standard library and overlays are built resiliently when SWIFT_STDLIB_STABLE_ABI=On.
if(SWIFTFILE_IS_STDLIB AND SWIFT_STDLIB_STABLE_ABI)
list(APPEND swift_flags "-enable-library-evolution")
list(APPEND swift_flags "-Xfrontend" "-library-level" "-Xfrontend" "api")
list(APPEND swift_flags "-library-level" "api")
list(APPEND swift_flags "-Xfrontend" "-require-explicit-availability=ignore")
endif()

if("${SWIFT_SDK_${SWIFTFILE_SDK}_THREADING_PACKAGE}" STREQUAL "none")
Expand Down
2 changes: 1 addition & 1 deletion test/ClangImporter/availability_spi_as_unavailable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public let c: SPIInterface1 // expected-error{{cannot use class 'SPIInterface1'
public let d: SPIInterface2 // expected-error{{cannot use class 'SPIInterface2' here; it is an SPI imported from 'SPIContainer'}}

@inlinable
public func inlinableUsingSPI() {
public func inlinableUsingSPI() { // expected-warning{{public declarations should have an availability attribute with an introduction version}}
SharedInterface.foo() // expected-error{{class method 'foo()' cannot be used in an '@inlinable' function because it is an SPI imported from 'SPIContainer'}}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,6 @@ public let c: SPIInterface1 // expected-error{{cannot use class 'SPIInterface1'
public let d: SPIInterface2 // expected-error{{cannot use class 'SPIInterface2' here; it is an SPI imported from '__ObjC'}}

@inlinable
public func inlinableUsingSPI() {
public func inlinableUsingSPI() { // expected-warning{{public declarations should have an availability attribute with an introduction version}}
SharedInterface.foo() // expected-error{{class method 'foo()' cannot be used in an '@inlinable' function because it is an SPI imported from '__ObjC'}}
}
1 change: 1 addition & 0 deletions test/SPI/spi-only-and-library-level.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ public struct LibStruct {}
@_spiOnly import Lib

public func publicClient() -> LibStruct { fatalError() } // expected-error {{cannot use struct 'LibStruct' here; 'Lib' was imported for SPI only}}
// expected-warning @-1 {{public declarations should have an availability attribute with an introduction version}}
@_spi(X) public func spiClient() -> LibStruct { fatalError() }

//--- SPILib.swift
Expand Down
2 changes: 1 addition & 1 deletion test/Sema/spi-available-inline.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ public class MacOSSPIClass { public init() {} }
@_spi_available(iOS 8.0, *)
public class iOSSPIClass { public init() {} }

@inlinable public func foo() {
@inlinable public func foo() { // expected-warning{{public declarations should have an availability attribute with an introduction version}}
_ = MacOSSPIClass() // expected-error {{class 'MacOSSPIClass' cannot be used in an '@inlinable' function because it is SPI}}
_ = iOSSPIClass()
}
4 changes: 2 additions & 2 deletions test/attr/attr_inlinable_available.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@


// Check that `-library-level api` implies `-target-min-inlining-version min`
// RUN: %target-typecheck-verify-swift -swift-version 5 -enable-library-evolution -module-name Test -target %target-next-stable-abi-triple -library-level api
// RUN: %target-typecheck-verify-swift -swift-version 5 -enable-library-evolution -module-name Test -target %target-next-stable-abi-triple -library-level api -require-explicit-availability=ignore


// Check that these rules are only applied when requested and that at least some
Expand All @@ -24,7 +24,7 @@

// Check that -target-min-inlining-version overrides -library-level, allowing
// library owners to disable this behavior for API libraries if needed.
// RUN: not %target-typecheck-verify-swift -swift-version 5 -enable-library-evolution -module-name Test -target %target-next-stable-abi-triple -target-min-inlining-version target -library-level api 2>&1 | %FileCheck --check-prefix NON_MIN %s
// RUN: not %target-typecheck-verify-swift -swift-version 5 -enable-library-evolution -module-name Test -target %target-next-stable-abi-triple -target-min-inlining-version target -library-level api -require-explicit-availability=ignore 2>&1 | %FileCheck --check-prefix NON_MIN %s


// Check that we respect -target-min-inlining-version by cranking it up high
Expand Down
Loading