Ante:一种融合借用检查与引用计数的新方法
Ante: A new way to blend borrow checking and reference counting

原始链接: https://verdagon.dev/blog/ante-blending-borrowing-rc

Ante 引入了“形状稳定性”(shape-stability)这一概念,确保对具有稳定形状的数据的引用,即使在其他地方发生变动时依然有效。由于 Ante 保证对象在使用过程中不会被销毁或结构性变更,该语言允许同时存在对同一个结构体及其嵌套字段的多个可变引用。 与严格禁止多个可变借用以避免内存安全问题的 Rust 或 Swift 不同,Ante 的编译器能够识别出:如果一个实体的结构是稳定的,那么对其字段的修改并不会导致现有引用失效。这使得开发者可以实现诸如“自愈函数”或同时对父结构体及其子组件(例如,飞船及其引擎)进行可变访问等模式,且不会产生内存损坏的风险。通过优先考虑形状稳定性,Ante 在保持内存安全的同时,简化了所有权和借用规则。

Hacker News 最新 | 往期 | 评论 | 提问 | 展示 | 招聘 | 提交 登录 Ante:一种融合借用检查与引用计数的新方法 (verdagon.dev) g0xA52A2A 发布于 1 小时前,8 点 | 隐藏 | 往期 | 收藏 | 讨论 | 帮助 指南 | 常见问题 | 列表 | API | 安全 | 法律 | 申请 YC | 联系 搜索:
相关文章

原文

Shape-Stability

Ante has a concept of shape-stability, which means "a reference to something of stable shape is always valid 6 no matter what mutations are made elsewhere."

Because of this, Ante code can safely have multiple mutable borrow references to the same struct at the same time.

To set the stage, here's a heal function taking two mutable references to Entitys:

type Entity =
    energy: I32
    health: I32

heal (healer: mut Entity) (target: mut Entity) =
    healer.energy -= 10
    target.health += 10

In Ante, we can call heal with the same Entity for both parameters — for example, when an entity heals itself:

self_heal (entity: mut Entity) =
    heal entity entity

Mutating healer can't invalidate shared references to the Entity in any way, 7 so the compiler accepts this code as valid.

In other words, even though healer and target might point to the same Entity, this is memory safe: nothing here can destroy the Entity, so both references stay valid.

Now let's get a little more complicated.

Ante code can actually have multiple mutable borrow references to the same struct, or any of its struct fields, or any of their struct fields, at the same time.

For example, here we have a mutable borrow reference pointing at the ship, and another mutable borrow reference pointing at the ship's engine, at the same time.

type Engine =
    fuel: I32

type Spaceship =
    engine: Engine
    name: String

refuel (ship: mut Spaceship) =
    engine_alias: mut Engine = ship.engine

    
    ship.engine.fuel := 200
    engine_alias.fuel := 100

Ante knows this is completely memory safe, because during this function, nobody can destroy ship, and therefore nobody can destroy its engine or its fuel.

In other words, these references are to shape-stable data.

Those familiar with Rust and Swift will be surprised by this:

  • In Rust, we can't have multiple &mut references pointing to the same data. 8
  • In Swift, we also can't have multiple &mut references pointing to the same data.

Now let's add some reference counting into the mix!

联系我们 contact @ memedata.com