[预期愿景] Swift 的可选严格内存安全

  • Swift Community Gathering Feedback: The Language Steering Group is seeking feedback on a prospective vision for optional strict memory safety in Swift through a pull request. Vision documents describe the overall direction, and actual changes will come in separate proposals. More info about vision documents in the evolution process is available.
  • Prospective Vision - Optional Strict Memory Safety for Swift: Swift is default memory-safe with major features and standard library APIs being so. This document proposes an optional "strict" subset of Swift that prohibits unsafe features, intended for code bases where memory safety is crucial like security-critical libraries.
  • Introduction: Memory safety is a popular topic. Swift provides memory safety in four dimensions (lifetime, bounds, type, initialization) since its inception and strict concurrency checking extends it to thread safety. Providing memory safety doesn't mean no runtime failures; it just means errors can't escalate into safety property violations.
  • Unsafe Code: Swift has opt-outs for writing memory-unsafe code like certain language features and library constructs. The "unsafe" convention works in practice but isn't sufficient to identify all unsafe code. Some tasks require lower-level memory access via unsafe pointer types.
  • Strictly-safe Subset of Swift: For code bases where memory safety is more important than programmer convenience, a compiler option can be used to flag any use of unsafe code. The compiler would flag specific unsafe language features and mark certain library constructs as unsafe. An @unsafe attribute would also be added.
  • Accessing Contiguous Memory: Low-level access to contiguous memory is one area where safe counterparts don't exist. Non-escapable types allow the creation of memory-safe counterparts to unsafe buffer types like Span, improving memory safety when accessing array elements. Lifetime dependencies enhance the expressiveness of non-escaping types.
  • Expressing Memory-safe Interfaces for the C Family of Languages: The C family of languages lacks memory safety. Swift uses annotations in C headers to improve the projection of C APIs into Swift. Additional annotations can provide safer interoperability with C APIs, like using Clang bounds-safety attributes to create more convenient APIs. C++ offers further opportunities for improved safety by modeling lifetimes.
阅读 12
0 条评论