Skip to content

[Parser|Sema] Accept access level on imports with experimental flag #63912

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 2 commits into from
Feb 27, 2023
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
6 changes: 6 additions & 0 deletions include/swift/AST/Decl.h
Original file line number Diff line number Diff line change
Expand Up @@ -1395,6 +1395,12 @@ class ImportDecl final : public Decl,
/// the decls it references. Otherwise, returns an empty array.
ArrayRef<ValueDecl *> getDecls() const;

/// Access level of this import, either explicitly declared or implicit.
AccessLevel getAccessLevel() const;

/// Is the access level of this import implicit, aka a default import?
bool isAccessLevelImplicit() const;

const clang::Module *getClangModule() const {
return getClangNode().getClangModule();
}
Expand Down
10 changes: 10 additions & 0 deletions include/swift/AST/DiagnosticsSema.def
Original file line number Diff line number Diff line change
Expand Up @@ -2044,6 +2044,16 @@ ERROR(spi_only_imports_not_enabled, none,
"'@_spiOnly' requires setting the frontend flag '-experimental-spi-only-imports'",
())

// Access level on imports
ERROR(access_level_on_import_not_enabled, none,
"Access level on imports require '-enable-experimental-feature AccessLevelOnImport'",
())
ERROR(access_level_on_import_unsupported, none,
"The access level %0 is unsupported on imports: "
"only 'public', 'package', 'internal', 'fileprivate' and 'private' "
"are unsupported",
(DeclAttribute))

// Opaque return types
ERROR(opaque_type_invalid_constraint,none,
"an 'opaque' type must specify only 'Any', 'AnyObject', protocols, "
Expand Down
31 changes: 24 additions & 7 deletions include/swift/AST/Import.h
Original file line number Diff line number Diff line change
Expand Up @@ -584,14 +584,24 @@ struct AttributedImport {
/// attribute, this is the given access level.
Optional<AccessLevel> docVisibility;

/// Access level limiting how imported types can be exported.
AccessLevel accessLevel;

/// Location of the attribute that defined \c accessLevel. Also indicates
/// if the access level was implicit or explicit.
SourceLoc accessLevelLoc;

AttributedImport(ModuleInfo module, SourceLoc importLoc = SourceLoc(),
ImportOptions options = ImportOptions(),
StringRef filename = {}, ArrayRef<Identifier> spiGroups = {},
SourceRange preconcurrencyRange = {},
Optional<AccessLevel> docVisibility = None)
Optional<AccessLevel> docVisibility = None,
AccessLevel accessLevel = AccessLevel::Public,
SourceLoc accessLevelLoc = SourceLoc())
: module(module), importLoc(importLoc), options(options),
sourceFileArg(filename), spiGroups(spiGroups),
preconcurrencyRange(preconcurrencyRange), docVisibility(docVisibility) {
preconcurrencyRange(preconcurrencyRange), docVisibility(docVisibility),
accessLevel(accessLevel), accessLevelLoc(accessLevelLoc) {
assert(!(options.contains(ImportFlags::Exported) &&
options.contains(ImportFlags::ImplementationOnly)) ||
options.contains(ImportFlags::Reserved));
Expand All @@ -601,15 +611,18 @@ struct AttributedImport {
AttributedImport(ModuleInfo module, AttributedImport<OtherModuleInfo> other)
: AttributedImport(module, other.importLoc, other.options,
other.sourceFileArg, other.spiGroups,
other.preconcurrencyRange, other.docVisibility) { }
other.preconcurrencyRange, other.docVisibility,
other.accessLevel, other.accessLevelLoc) { }

friend bool operator==(const AttributedImport<ModuleInfo> &lhs,
const AttributedImport<ModuleInfo> &rhs) {
return lhs.module == rhs.module &&
lhs.options.toRaw() == rhs.options.toRaw() &&
lhs.sourceFileArg == rhs.sourceFileArg &&
lhs.spiGroups == rhs.spiGroups &&
lhs.docVisibility == rhs.docVisibility;
lhs.docVisibility == rhs.docVisibility &&
lhs.accessLevel == rhs.accessLevel &&
lhs.accessLevelLoc == rhs.accessLevelLoc;
}

AttributedImport<ImportedModule> getLoaded(ModuleDecl *loadedModule) const {
Expand Down Expand Up @@ -761,14 +774,16 @@ struct DenseMapInfo<swift::AttributedImport<ModuleInfo>> {
SourceLocDMI::getEmptyKey(),
ImportOptionsDMI::getEmptyKey(),
StringRefDMI::getEmptyKey(),
{}, {}, None);
{}, {}, None,
swift::AccessLevel::Public, {});
}
static inline AttributedImport getTombstoneKey() {
return AttributedImport(ModuleInfoDMI::getTombstoneKey(),
SourceLocDMI::getEmptyKey(),
ImportOptionsDMI::getTombstoneKey(),
StringRefDMI::getTombstoneKey(),
{}, {}, None);
{}, {}, None,
swift::AccessLevel::Public, {});
}
static inline unsigned getHashValue(const AttributedImport &import) {
return detail::combineHashValue(
Expand All @@ -783,7 +798,9 @@ struct DenseMapInfo<swift::AttributedImport<ModuleInfo>> {
ImportOptionsDMI::isEqual(a.options, b.options) &&
StringRefDMI::isEqual(a.sourceFileArg, b.sourceFileArg) &&
a.spiGroups == b.spiGroups &&
a.docVisibility == b.docVisibility;
a.docVisibility == b.docVisibility &&
a.accessLevel == b.accessLevel &&
a.accessLevelLoc == b.accessLevelLoc;
}
};
}
Expand Down
2 changes: 2 additions & 0 deletions include/swift/Basic/Features.def
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,9 @@ EXPERIMENTAL_FEATURE(MoveOnlyClasses, true)
EXPERIMENTAL_FEATURE(OneWayClosureParameters, false)
EXPERIMENTAL_FEATURE(TypeWitnessSystemInference, false)
EXPERIMENTAL_FEATURE(LayoutPrespecialization, true)

EXPERIMENTAL_FEATURE(ModuleInterfaceExportAs, true)
EXPERIMENTAL_FEATURE(AccessLevelOnImport, false)

/// Whether to enable experimental differentiable programming features:
/// `@differentiable` declaration attribute, etc.
Expand Down
4 changes: 4 additions & 0 deletions lib/AST/ASTPrinter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3119,6 +3119,10 @@ static bool usesFeatureModuleInterfaceExportAs(Decl *decl) {
return false;
}

static bool usesFeatureAccessLevelOnImport(Decl *decl) {
return false;
}

static bool usesFeatureNamedOpaqueTypes(Decl *decl) {
return false;
}
Expand Down
22 changes: 22 additions & 0 deletions lib/AST/Decl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1343,6 +1343,28 @@ ArrayRef<ValueDecl *> ImportDecl::getDecls() const {
ScopedImportLookupRequest{mutableThis}, {});
}

AccessLevel ImportDecl::getAccessLevel() const {
if (auto attr = getAttrs().getAttribute<AccessControlAttr>()) {
return attr->getAccess();
}

auto &LangOpts = getASTContext().LangOpts;
if (LangOpts.isSwiftVersionAtLeast(6) &&
LangOpts.hasFeature(Feature::AccessLevelOnImport)) {
// Tentative Swift 6 mode where the default import is internal.
return AccessLevel::Internal;
} else {
return AccessLevel::Public;
}
}

bool ImportDecl::isAccessLevelImplicit() const {
if (auto attr = getAttrs().getAttribute<AccessControlAttr>()) {
return false;
}
return true;
}

void NominalTypeDecl::setConformanceLoader(LazyMemberLoader *lazyLoader,
uint64_t contextData) {
assert(!Bits.NominalTypeDecl.HasLazyConformances &&
Expand Down
5 changes: 5 additions & 0 deletions lib/Sema/ImportResolution.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -543,6 +543,11 @@ UnboundImport::UnboundImport(ImportDecl *ID)
if (ID->getAttrs().hasAttribute<ImplementationOnlyAttr>())
import.options |= ImportFlags::ImplementationOnly;

import.accessLevel = ID->getAccessLevel();
if (auto attr = ID->getAttrs().getAttribute<AccessControlAttr>()) {
import.accessLevelLoc = attr->getLocation();
}

if (ID->getAttrs().hasAttribute<SPIOnlyAttr>())
import.options |= ImportFlags::SPIOnly;

Expand Down
15 changes: 14 additions & 1 deletion lib/Sema/TypeCheckAttr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -934,7 +934,7 @@ void AttributeChecker::visitLazyAttr(LazyAttr *attr) {
bool AttributeChecker::visitAbstractAccessControlAttr(
AbstractAccessControlAttr *attr) {
// Access control attr may only be used on value decls and extensions.
if (!isa<ValueDecl>(D) && !isa<ExtensionDecl>(D)) {
if (!isa<ValueDecl>(D) && !isa<ExtensionDecl>(D) && !isa<ImportDecl>(D)) {
diagnoseAndRemoveAttr(attr, diag::invalid_decl_modifier, attr);
return true;
}
Expand All @@ -960,6 +960,19 @@ bool AttributeChecker::visitAbstractAccessControlAttr(
return true;
}

if (auto importDecl = dyn_cast<ImportDecl>(D)) {
if (!D->getASTContext().LangOpts.hasFeature(Feature::AccessLevelOnImport)) {
diagnoseAndRemoveAttr(attr, diag::access_level_on_import_not_enabled);
return true;
}

if (attr->getAccess() == AccessLevel::Open) {
diagnoseAndRemoveAttr(attr, diag::access_level_on_import_unsupported,
attr);
return true;
}
}

return false;
}

Expand Down
27 changes: 27 additions & 0 deletions test/Sema/access-level-import-flag-check.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// RUN: %empty-directory(%t)
// RUN: split-file %s %t

/// Build the libraries.
// RUN: %target-swift-frontend -emit-module %t/PublicLib.swift -o %t
// RUN: %target-swift-frontend -emit-module %t/PackageLib.swift -o %t
// RUN: %target-swift-frontend -emit-module %t/InternalLib.swift -o %t
// RUN: %target-swift-frontend -emit-module %t/FileprivateLib.swift -o %t
// RUN: %target-swift-frontend -emit-module %t/PrivateLib.swift -o %t

/// Check flag requirement, without and with the flag.
// RUN: %target-swift-frontend -typecheck %t/ClientWithoutTheFlag.swift -I %t -verify
// RUN: %target-swift-frontend -typecheck %t/ClientWithoutTheFlag.swift -I %t \
// RUN: -enable-experimental-feature AccessLevelOnImport

//--- PublicLib.swift
//--- PackageLib.swift
//--- InternalLib.swift
//--- FileprivateLib.swift
//--- PrivateLib.swift

//--- ClientWithoutTheFlag.swift
public import PublicLib // expected-error@:1 {{Access level on imports require '-enable-experimental-feature AccessLevelOnImport'}}
package import PackageLib // expected-error@:1 {{Access level on imports require '-enable-experimental-feature AccessLevelOnImport'}}
internal import InternalLib // expected-error@:1 {{Access level on imports require '-enable-experimental-feature AccessLevelOnImport'}}
fileprivate import FileprivateLib // expected-error@:1 {{Access level on imports require '-enable-experimental-feature AccessLevelOnImport'}}
private import PrivateLib // expected-error@:1 {{Access level on imports require '-enable-experimental-feature AccessLevelOnImport'}}
29 changes: 29 additions & 0 deletions test/Sema/access-level-import-parsing.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// RUN: %empty-directory(%t)
// RUN: split-file %s %t

/// Build the libraries.
// RUN: %target-swift-frontend -emit-module %t/PublicLib.swift -o %t
// RUN: %target-swift-frontend -emit-module %t/PackageLib.swift -o %t
// RUN: %target-swift-frontend -emit-module %t/InternalLib.swift -o %t
// RUN: %target-swift-frontend -emit-module %t/FileprivateLib.swift -o %t
// RUN: %target-swift-frontend -emit-module %t/PrivateLib.swift -o %t
// RUN: %target-swift-frontend -emit-module %t/OpenLib.swift -o %t

/// Check that all access levels are accepted, except for 'open'.
// RUN: %target-swift-frontend -typecheck %t/Client.swift -I %t \
// RUN: -enable-experimental-feature AccessLevelOnImport -verify

//--- PublicLib.swift
//--- PackageLib.swift
//--- InternalLib.swift
//--- FileprivateLib.swift
//--- PrivateLib.swift
//--- OpenLib.swift

//--- Client.swift
public import PublicLib
package import PackageLib
internal import InternalLib
fileprivate import FileprivateLib
private import PrivateLib
open import OpenLib // expected-error {{The access level 'open' is unsupported on imports: only 'public', 'package', 'internal', 'fileprivate' and 'private' are unsupported}}
2 changes: 1 addition & 1 deletion test/attr/accessibility.swift
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ var unterminatedEmptySubject = 0
duplicateAttr(1) // expected-error{{argument passed to call that takes no arguments}}

// CHECK ALLOWED DECLS
private import Swift // expected-error {{'private' modifier cannot be applied to this declaration}} {{1-9=}}
private import Swift // expected-error {{Access level on imports require '-enable-experimental-feature AccessLevelOnImport}}
private(set) infix operator ~~~ // expected-error {{'private' modifier cannot be applied to this declaration}} {{1-14=}}

private typealias MyInt = Int
Expand Down
2 changes: 1 addition & 1 deletion utils/gyb_syntax_support/AttributeKinds.py
Original file line number Diff line number Diff line change
Expand Up @@ -825,7 +825,7 @@ def __init__(self, name, swift_name=None):
code=44),
DeclAttribute('private', 'AccessControl',
OnFunc, OnAccessor, OnExtension, OnGenericType, OnVar, OnSubscript,
OnConstructor, OnMacro,
OnConstructor, OnMacro, OnImport,
DeclModifier,
NotSerialized,
ABIStableToAdd, ABIStableToRemove, APIStableToAdd, APIStableToRemove,
Expand Down