Wednesday, January 22, 2025

Swift Proposal: Opt-in Strict Memory Safety Checking

SE-0458:

For example, Swift solves null references with optional types. Statically, Swift prevents you from using an optional reference without checking it first. If you’re sure it’s non-null, you can use the ! operator, which is safe because Swift will dynamically check for nil. If you really can’t afford that dynamic check, you can use unsafelyUnwrapped. This can still be correct if you can prove that the reference is definitely non-null for some reason that Swift doesn’t know. But it is an unsafe feature because it admits violations if you’re wrong.

[…]

A compiler flag -strict-memory-safety that enables warnings for all uses of unsafe constructs within a given module. All warnings will be in the diagnostic group Unsafe, enabling precise control over memory-safety-related warnings per SE-0443. When strict memory safety is enabled, the StrictMemorySafety feature will be set: #if hasFeature(StrictMemorySafety) can be used to detect when Swift code is being compiled in this mode.

[…]

Because UnsafeBufferPointer and UnsafePointer are @unsafe types, this code will get a warning regardless of whether the declarations were marked @unsafe, because having unsafe types in the signature of a declaration implies that they are @unsafe. This helps us identify more unsafe code even when the libraries we depend on haven’t enabled strict safety checking themselves.

To suppress these warnings, the expressions involving unsafe code must be marked with unsafe in the same manner as one would mark a throwing expression with try or an asynchronous expression with async.

Previously:

Comments RSS · Twitter · Mastodon

Leave a Comment