Skip to content

Add @_private(from: "SourceFile.swift") imports #20428

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 7 commits into from
Nov 9, 2018
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
4 changes: 4 additions & 0 deletions include/swift/AST/Attr.def
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,10 @@ DECL_ATTR(_dynamicReplacement, DynamicReplacement,
SIMPLE_DECL_ATTR(_borrowed, Borrowed,
OnVar | OnSubscript | UserInaccessible |
NotSerialized, 81)
DECL_ATTR(_private, PrivateImport,
OnImport |
UserInaccessible |
NotSerialized, 82)

#undef TYPE_ATTR
#undef DECL_ATTR_ALIAS
Expand Down
20 changes: 20 additions & 0 deletions include/swift/AST/Attr.h
Original file line number Diff line number Diff line change
Expand Up @@ -901,6 +901,26 @@ class ObjCAttr final : public DeclAttribute,
}
};

class PrivateImportAttr final
: public DeclAttribute {
StringRef SourceFile;

PrivateImportAttr(SourceLoc atLoc, SourceRange baseRange,
StringRef sourceFile, SourceRange parentRange);

public:
static PrivateImportAttr *create(ASTContext &Ctxt, SourceLoc AtLoc,
SourceLoc PrivateLoc, SourceLoc LParenLoc,
StringRef sourceFile, SourceLoc RParenLoc);

StringRef getSourceFile() const {
return SourceFile;
}
static bool classof(const DeclAttribute *DA) {
return DA->getKind() == DAK_PrivateImport;
}
};

/// The @_dynamicReplacement(for:) attribute.
class DynamicReplacementAttr final
: public DeclAttribute,
Expand Down
7 changes: 5 additions & 2 deletions include/swift/AST/Decl.h
Original file line number Diff line number Diff line change
Expand Up @@ -573,7 +573,7 @@ class alignas(1 << DeclAlignInBits) Decl {
HasAnyUnavailableValues : 1
);

SWIFT_INLINE_BITFIELD(ModuleDecl, TypeDecl, 1+1+1+1,
SWIFT_INLINE_BITFIELD(ModuleDecl, TypeDecl, 1+1+1+1+1,
/// If the module was or is being compiled with `-enable-testing`.
TestingEnabled : 1,

Expand All @@ -586,7 +586,10 @@ class alignas(1 << DeclAlignInBits) Decl {
RawResilienceStrategy : 1,

/// Whether all imports have been resolved. Used to detect circular imports.
HasResolvedImports : 1
HasResolvedImports : 1,

// If the module was or is being compiled with `-enable-private-imports`.
PrivateImportsEnabled : 1
);

SWIFT_INLINE_BITFIELD(PrecedenceGroupDecl, Decl, 1+2,
Expand Down
9 changes: 9 additions & 0 deletions include/swift/AST/DiagnosticsParse.def
Original file line number Diff line number Diff line change
Expand Up @@ -1417,6 +1417,15 @@ ERROR(attr_dynamic_replacement_expected_for,none,
ERROR(attr_dynamic_replacement_expected_colon,none,
"expected ':' after @_dynamicReplacement(for", ())

ERROR(attr_private_import_expected_rparen,none,
"expected ')' after function name for @_private", ())
ERROR(attr_private_import_expected_sourcefile, none,
"expected 'sourceFile' in '_private' attribute", ())
ERROR(attr_private_import_expected_sourcefile_name,none,
"expected a source file name in @_private(sourceFile:)", ())
Copy link
Contributor

Choose a reason for hiding this comment

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

I'm a bit confused, is it @_private(sourceFile:) or @_private(from:) (like in the commit message :) )

ERROR(attr_private_import_expected_colon,none,
"expected ':' after @_private(sourceFile", ())

// opened
ERROR(opened_attribute_expected_lparen,none,
"expected '(' after 'opened' attribute", ())
Expand Down
4 changes: 4 additions & 0 deletions include/swift/AST/DiagnosticsSema.def
Original file line number Diff line number Diff line change
Expand Up @@ -759,6 +759,10 @@ ERROR(ambiguous_decl_in_module,none,
ERROR(module_not_testable,none,
"module %0 was not compiled for testing", (Identifier))

ERROR(module_not_compiled_for_private_import,none,
"module %0 was not compiled for private import", (Identifier))


// Operator decls
ERROR(ambiguous_operator_decls,none,
"ambiguous operator declarations found for operator", ())
Expand Down
53 changes: 48 additions & 5 deletions include/swift/AST/Module.h
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,15 @@ class ModuleDecl : public DeclContext, public TypeDecl {
Bits.ModuleDecl.TestingEnabled = enabled;
}

/// Returns true if this module was or is begin compile with
/// `-enable-private-imports`.
bool arePrivateImportsEnabled() const {
return Bits.ModuleDecl.PrivateImportsEnabled;
}
void setPrivateImportsEnabled(bool enabled = true) {
Bits.ModuleDecl.PrivateImportsEnabled = true;
}

/// Returns true if there was an error trying to load this module.
bool failedToLoad() const {
return Bits.ModuleDecl.FailedToLoad;
Expand Down Expand Up @@ -844,20 +853,38 @@ class SourceFile final : public FileUnit {

/// This source file has access to testable declarations in the imported
/// module.
Testable = 0x2
Testable = 0x2,

/// This source file has access to private declarations in the imported
/// module.
PrivateImport = 0x4,
};

/// \see ImportFlags
using ImportOptions = OptionSet<ImportFlags>;

typedef std::pair<ImportOptions, StringRef> ImportOptionsAndFilename;

struct ImportedModuleDesc {
ModuleDecl::ImportedModule module;
ImportOptions importOptions;
StringRef filename;

ImportedModuleDesc(ModuleDecl::ImportedModule module, ImportOptions options)
: module(module), importOptions(options) {}
ImportedModuleDesc(ModuleDecl::ImportedModule module, ImportOptions options,
StringRef filename)
: module(module), importOptions(options), filename(filename) {}
};

private:
std::unique_ptr<LookupCache> Cache;
LookupCache &getCache() const;

/// This is the list of modules that are imported by this module.
///
/// This is filled in by the Name Binding phase.
ArrayRef<std::pair<ModuleDecl::ImportedModule, ImportOptions>> Imports;
ArrayRef<ImportedModuleDesc> Imports;

/// A unique identifier representing this file; used to mark private decls
/// within the file to keep them from conflicting with other files in the
Expand Down Expand Up @@ -961,10 +988,9 @@ class SourceFile final : public FileUnit {
ImplicitModuleImportKind ModImpKind, bool KeepParsedTokens = false,
bool KeepSyntaxTree = false);

void
addImports(ArrayRef<std::pair<ModuleDecl::ImportedModule, ImportOptions>> IM);
void addImports(ArrayRef<ImportedModuleDesc> IM);

bool hasTestableImport(const ModuleDecl *module) const;
bool hasTestableOrPrivateImport(AccessLevel accessLevel, const ValueDecl *ofDecl) const;

void clearLookupCache();

Expand Down Expand Up @@ -1224,12 +1250,29 @@ class LoadedFile : public FileUnit {
assert(classof(this) && "invalid kind");
}

/// A map from private/fileprivate decls to the file they were defined in.
llvm::DenseMap<const ValueDecl *, Identifier> FilenameForPrivateDecls;
Copy link
Contributor

Choose a reason for hiding this comment

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

Can you explain why this is necessary? It seems like it should be an on-demand on-disk hash table like the private discriminator map.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This works in the same way as PrivateDiscriminatorsByValue when we deserialize a value decl we put it in the map.

When we need to determine hasPrivateImport(const swift::ValueDecl *ofDecl) we check it.

Copy link
Contributor

Choose a reason for hiding this comment

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

Oops. I didn't realize we did that eagerly for private discriminators too.

…and now I'm working through the reasoning that leads there again: you can't easily look up a decl pointer in a module. My mistake!


public:

/// Returns an arbitrary string representing the storage backing this file.
///
/// This is usually a filesystem path.
virtual StringRef getFilename() const;

void addFilenameForPrivateDecl(const ValueDecl *decl, Identifier id) {
assert(!FilenameForPrivateDecls.count(decl) ||
FilenameForPrivateDecls[decl] == id);
FilenameForPrivateDecls[decl] = id;
}

StringRef getFilenameForPrivateDecl(const ValueDecl *decl) {
auto it = FilenameForPrivateDecls.find(decl);
if (it == FilenameForPrivateDecls.end())
return StringRef();
return it->second.str();
}

/// Look up an operator declaration.
///
/// \param name The operator name ("+", ">>", etc.)
Expand Down
5 changes: 5 additions & 0 deletions include/swift/Frontend/FrontendOptions.h
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,11 @@ class FrontendOptions {
/// \see ModuleDecl::isTestingEnabled
bool EnableTesting = false;

/// Indicates whether we are compiling for private imports.
///
/// \see ModuleDecl::arePrivateImportsEnabled
bool EnablePrivateImports = false;

/// Enables the "fully resilient" resilience strategy.
///
/// \see ResilienceStrategy::Resilient
Expand Down
4 changes: 4 additions & 0 deletions include/swift/Option/Options.td
Original file line number Diff line number Diff line change
Expand Up @@ -791,6 +791,10 @@ def enable_testing : Flag<["-"], "enable-testing">,
Flags<[FrontendOption, NoInteractiveOption, HelpHidden]>,
HelpText<"Allows this module's internal API to be accessed for testing">;

def enable_private_imports : Flag<["-"], "enable-private-imports">,
Flags<[FrontendOption, NoInteractiveOption, HelpHidden]>,
HelpText<"Allows this module's internal and private API to be accessed">;

def sanitize_EQ : CommaJoined<["-"], "sanitize=">,
Flags<[FrontendOption, NoInteractiveOption]>, MetaVarName<"<check>">,
HelpText<"Turn on runtime checks for erroneous behavior.">;
Expand Down
1 change: 1 addition & 0 deletions include/swift/Serialization/DeclTypeRecordNodes.def
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,7 @@ OTHER(SUBSTITUTION_MAP, 236)

OTHER(LOCAL_DISCRIMINATOR, 237)
OTHER(PRIVATE_DISCRIMINATOR, 238)
OTHER(FILENAME_FOR_PRIVATE, 239)

OTHER(ABSTRACT_PROTOCOL_CONFORMANCE, 240)
OTHER(NORMAL_PROTOCOL_CONFORMANCE, 241)
Expand Down
15 changes: 13 additions & 2 deletions include/swift/Serialization/ModuleFormat.h
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ const uint16_t SWIFTMODULE_VERSION_MAJOR = 0;
/// describe what change you made. The content of this comment isn't important;
/// it just ensures a conflict if two people change the module format.
/// Don't worry about adhering to the 80-column limit for this line.
const uint16_t SWIFTMODULE_VERSION_MINOR = 462; // Last change: Add dynamicReplacement(for:)
const uint16_t SWIFTMODULE_VERSION_MINOR = 463; // Last change: enable-private-imports

using DeclIDField = BCFixed<31>;

Expand Down Expand Up @@ -592,7 +592,8 @@ namespace options_block {
XCC,
IS_SIB,
IS_TESTABLE,
RESILIENCE_STRATEGY
RESILIENCE_STRATEGY,
ARE_PRIVATE_IMPORTS_ENABLED
};

using SDKPathLayout = BCRecordLayout<
Expand All @@ -614,6 +615,10 @@ namespace options_block {
IS_TESTABLE
>;

using ArePrivateImportsEnabledLayout = BCRecordLayout<
ARE_PRIVATE_IMPORTS_ENABLED
>;

This comment was marked as outdated.


using ResilienceStrategyLayout = BCRecordLayout<
RESILIENCE_STRATEGY,
BCFixed<2>
Expand Down Expand Up @@ -1309,6 +1314,11 @@ namespace decls_block {
BCVBR<2> // context-scoped discriminator counter
>;

using FilenameForPrivateLayout = BCRecordLayout<
FILENAME_FOR_PRIVATE,
IdentifierIDField // the file name, as an identifier
>;

/// A placeholder for lack of concrete conformance information.
using AbstractProtocolConformanceLayout = BCRecordLayout<
ABSTRACT_PROTOCOL_CONFORMANCE,
Expand Down Expand Up @@ -1513,6 +1523,7 @@ namespace decls_block {
= BCRecordLayout<RestatedObjCConformance_DECL_ATTR>;
using ClangImporterSynthesizedTypeDeclAttrLayout
= BCRecordLayout<ClangImporterSynthesizedType_DECL_ATTR>;
using PrivateImportDeclAttrLayout = BCRecordLayout<PrivateImport_DECL_ATTR>;

using InlineDeclAttrLayout = BCRecordLayout<
Inline_DECL_ATTR,
Expand Down
5 changes: 5 additions & 0 deletions include/swift/Serialization/Validation.h
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ class ExtendedValidationInfo {
SmallVector<StringRef, 4> ExtraClangImporterOpts;
StringRef SDKPath;
struct {
unsigned ArePrivateImportsEnabled : 1;
unsigned IsSIB : 1;
unsigned IsTestable : 1;
unsigned ResilienceStrategy : 2;
Expand All @@ -117,6 +118,10 @@ class ExtendedValidationInfo {
void setIsSIB(bool val) {
Bits.IsSIB = val;
}
bool arePrivateImportsEnabled() { return Bits.ArePrivateImportsEnabled; }
void setPrivateImportsEnabled(bool enabled) {
Bits.ArePrivateImportsEnabled = enabled;
}
bool isTestable() const { return Bits.IsTestable; }
void setIsTestable(bool val) {
Bits.IsTestable = val;
Expand Down
27 changes: 26 additions & 1 deletion lib/AST/Attr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,12 @@ bool DeclAttribute::printImpl(ASTPrinter &Printer, const PrintOptions &Options,
}
break;
}

case DAK_PrivateImport: {
Printer.printAttrName("@_private(sourceFile: \"");
Copy link
Contributor

Choose a reason for hiding this comment

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

Nitpick: The parens and labels shouldn't be part of printAttrName (that's what controls the highlighting). Take a look at DAK_Available.

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 see.

Printer << cast<PrivateImportAttr>(this)->getSourceFile() << "\")";
break;
}

case DAK_SwiftNativeObjCRuntimeBase: {
auto *attr = cast<SwiftNativeObjCRuntimeBaseAttr>(this);
Expand Down Expand Up @@ -547,7 +553,8 @@ bool DeclAttribute::printImpl(ASTPrinter &Printer, const PrintOptions &Options,
}

case DAK_DynamicReplacement: {
Printer.printAttrName("@_dynamicReplacement(for: \"");
Printer.printAttrName("@_dynamicReplacement");
Printer << "(for: \"";
auto *attr = cast<DynamicReplacementAttr>(this);
Printer << attr->getReplacedFunctionName() << "\")";
break;
Expand Down Expand Up @@ -621,6 +628,8 @@ StringRef DeclAttribute::getAttrName() const {
return "objc";
case DAK_DynamicReplacement:
return "_dynamicReplacement";
case DAK_PrivateImport:
return "_private";
case DAK_RestatedObjCConformance:
return "_restatedObjCConformance";
case DAK_Inline: {
Expand Down Expand Up @@ -785,6 +794,22 @@ ObjCAttr *ObjCAttr::clone(ASTContext &context) const {
return attr;
}

PrivateImportAttr::PrivateImportAttr(SourceLoc atLoc, SourceRange baseRange,
StringRef sourceFile,
SourceRange parenRange)
: DeclAttribute(DAK_PrivateImport, atLoc, baseRange, /*Implicit=*/false),
SourceFile(sourceFile) {}

PrivateImportAttr *PrivateImportAttr::create(ASTContext &Ctxt, SourceLoc AtLoc,
SourceLoc PrivateLoc,
SourceLoc LParenLoc,
StringRef sourceFile,
SourceLoc RParenLoc) {
return new (Ctxt)
PrivateImportAttr(AtLoc, SourceRange(PrivateLoc, RParenLoc), sourceFile,
SourceRange(LParenLoc, RParenLoc));
}

DynamicReplacementAttr::DynamicReplacementAttr(SourceLoc atLoc,
SourceRange baseRange,
DeclName name,
Expand Down
Loading