Add @safe(unchecked) to allow unsafe code within a declaration.

Introduce an attribute to allow unsafe code within the annotated
declaration without presenting an unsafe interface to users. This is,
by its nature, and unsafe construct, and is used to document where
unsafe behavior is encapsulated in safe constructs.

There is an optional message that can be used as part of an audit
trail.
This commit is contained in:
Doug Gregor
2024-12-13 11:36:40 -08:00
parent cf7fcf2da9
commit e260d65f71
13 changed files with 138 additions and 5 deletions

View File

@@ -2837,6 +2837,26 @@ public:
UNIMPLEMENTED_CLONE(RawLayoutAttr)
};
class SafeAttr final : public DeclAttribute {
public:
/// The optional message.
const StringRef message;
SafeAttr(SourceLoc atLoc, SourceRange range, StringRef message,
bool isImplicit = false)
: DeclAttribute(DeclAttrKind::Safe, atLoc, range, isImplicit),
message(message) { }
static bool classof(const DeclAttribute *DA) {
return DA->getKind() == DeclAttrKind::Safe;
}
/// Create a copy of this attribute.
SafeAttr *clone(ASTContext &ctx) const {
return new (ctx) SafeAttr(AtLoc, Range, message, isImplicit());
}
};
class LifetimeAttr final : public DeclAttribute {
LifetimeEntry *entry;

View File

@@ -504,8 +504,8 @@ SIMPLE_DECL_ATTR(sensitive, Sensitive,
159)
SIMPLE_DECL_ATTR(unsafe, Unsafe,
OnAbstractFunction | OnSubscript | OnVar | OnMacro | OnNominalType | OnExtension |
UserInaccessible |
OnAbstractFunction | OnSubscript | OnVar | OnMacro | OnNominalType |
OnExtension | OnTypeAlias | UserInaccessible |
ABIStableToAdd | ABIStableToRemove | APIBreakingToAdd | APIStableToRemove,
160)
@@ -517,7 +517,13 @@ SIMPLE_DECL_ATTR(_addressableSelf, AddressableSelf,
OnAccessor | OnConstructor | OnFunc | OnSubscript | ABIBreakingToAdd | ABIStableToRemove | APIBreakingToAdd | APIStableToRemove | UserInaccessible,
162)
LAST_DECL_ATTR(AddressableSelf)
DECL_ATTR(safe, Safe,
OnAbstractFunction | OnSubscript | OnVar | OnMacro | OnNominalType |
OnExtension | OnTypeAlias | UserInaccessible |
ABIStableToAdd | ABIStableToRemove | APIBreakingToAdd | APIStableToRemove,
163)
LAST_DECL_ATTR(Safe)
#undef DECL_ATTR_ALIAS
#undef CONTEXTUAL_DECL_ATTR_ALIAS

View File

@@ -2106,6 +2106,9 @@ ERROR(parser_new_parser_errors,none,
"new Swift parser generated errors for code that C++ parser accepted",
())
ERROR(safe_attr_unchecked,none,
"'@safe' attribute must be written as '@safe(unchecked)'", ())
// MARK: Reference Binding Diagnostics
ERROR(sil_markuncheckedreferencebinding_requires_attribute,none,
"mark_unchecked_reference_binding requires an attribute like [inout]", ())