阅读时间约 20 分钟

「SF-PLF」13 References

Programming Language Foundations - Typing Mutable References

Posted by Hux on March 13, 2019
SF (软件基础) PLF (编程语言基础) Coq 笔记

Hux: this chapter is very similar to TAPL - ch13 References But under a “formal verification” concept, it’s more interesting and practical and push you to think about it!

computational effects - “side effects” of computation - impure features

  • assign to mutable variables (reference cells, arrays, mutable record fields, etc.)
  • perform input and output to files, displays, or network connections;
  • make non-local transfers of control via exceptions, jumps, or continuations;
  • engage in inter-process synchronization and communication

The main extension will be dealing explicitly with a

  • store (or heap) and
  • pointers (or reference) that name store locations, or address

interesting refinement: type preservation

Definition

forms of assignments:

  • rare : Gallina - No
  • some : ML family - Explicit reference and dereference
  • most : C family - Implicit …

For formal study, use ML’s model.

Syntax

Types & Terms

T ::= 
    | Nat
    | Unit
    | T  T
    | Ref T

t ::= 
    | ...                Terms
    | ref t              allocation
    | !t                 dereference
    | t := t             assignment
    | l                  location
Inductive ty : Type :=
  | Nat : ty
  | Unit : ty
  | Arrow : ty  ty  ty
  | Ref : ty  ty.

Inductive tm : Type :=
  (* STLC with numbers: *)
  ...
  (* New terms: *)
  | unit : tm
  | ref : tm  tm
  | deref : tm  tm
  | assign : tm  tm  tm
  | loc : nat  tm.         (** 这里表示 l 的方式是 wrap 一个 nat as loc **)

Typing

                       Gamma |- t1 : T1
                   ------------------------                         (T_Ref)
                   Gamma |- ref t1 : Ref T1

                    Gamma |- t1 : Ref T11
                    ---------------------                         (T_Deref)
                      Gamma |- !t1 : T11

                    Gamma |- t1 : Ref T11
                      Gamma |- t2 : T11
                   ------------------------                      (T_Assign)
                   Gamma |- t1 := t2 : Unit

Values and Substitution

Inductive value : tm  Prop :=
  ...
  | v_unit :     value unit
  | v_loc  : l, value (loc l).  (* <-- 注意这里是一个 Π (l:nat) . value (loc l) *)
Fixpoint subst (x:string) (s:tm) (t:tm) : tm :=
  match t with
  ...
  | unit          t
  | ref t1        ref (subst x s t1)
  | deref t1      deref (subst x s t1)
  | assign t1 t2  assign (subst x s t1) (subst x s t2)
  | loc _         t
  end.

Pragmatics

Side Effects and Sequencing

r:=succ(!r); !r

can be desugar to

(\x:Unit. !r) (r:=succ(!r)).

then we can write some “imperative programming”

r:=succ(!r); 
r:=succ(!r); 
r:=succ(!r); 
!r

References and Aliasing

shared reference brings _shared state

let r = ref 5 in
let s = r in
s := 82;
(!r)+1

Shared State

thunks as methods


    let c = ref 0 in
    let incc = \_:Unit. (c := succ (!c); !c) in
    let decc = \_:Unit. (c := pred (!c); !c) in (
      incc unit; 
      incc unit;          -- in real PL: the concrete syntax is `incc()`
      decc unit
    )

Objects

constructor and encapsulation!


    newcounter =
      \_:Unit.            -- add `(self, init_val)` would make it more "real"
        let c = ref 0 in  -- private and only accessible via closure (特权方法)
        let incc = \_:Unit. (c := succ (!c); !c) in
        let decc = \_:Unit. (c := pred (!c); !c) in
        { i=incc, 
          d=decc  }       -- return a "record", or "struct", or "object"!
          

References to Compound Types (e.g. Function Type)

Previously, we use closure to represent map, with functional update 这里的”数组” (这个到底算不算数组估计都有争议,虽然的确提供了 index 但是这个显然是 O(n) 都不知道算不算 random access… 并不是 in-place update 里面的数据的,仅仅是一个 ref 包住的 map 而已 (仅仅是多了可以 shared

其实或许 list (ref nat) 也可以表达数组? 反正都是 O(n) 每次都 linear search 也一样……


    newarray = \_:Unit. ref (\n:Nat.0)
    lookup = \a:NatArray. \n:Nat. (!a) n   
    update = \a:NatArray. \m:Nat. \v:Nat.
               let oldf = !a in
               a := (\n:Nat. if equal m n then v else oldf n);

Null References

nullptr!

Deref a nullptr:

  • exception in Java/C#
  • insecure in C/C++ <– violate memory safety!!

    type Option T   = Unit + T
    type Nullable T = Option (Ref T)

Why is Option outside? think about C, nullptr is A special const location, like Unit (None in terms of datacon) here.

Garbage Collection

last issue: store de-allocation

w/o GC, extremely difficult to achieve type safety…if a primitive for “explicit deallocation” provided one can easily create dangling reference i.e. references -> deleted

One type-unsafe example: (pseudo code)


   a : Ref Nat = ref 1;       -- alloc loc 0
   free(a);                   -- free  loc 0
   b : Ref Bool = ref True;   -- alloc loc 0
   
   a := !a + 1                -- BOOM!

Operational Semantics

Locations

what should be the values of type Ref T?

ref allocate some memory/storage!

run-time store is essentially big array of bytes. different datatype need to allocate different size of space (region)

we think store as array of values, abstracting away different size of different values we use the word location here to prevent from modeling pointer arithmetic, which is un-trackable by most type system

location n is float doesn’t tell you anything about location n+4

Stores

we defined replace as Fixpoint since it’s computational and easier. The consequence is it has to be total.

Reduction

Typing

typing context:

Definition context := partial_map ty.

Store typings

why not just make a context a map of pair? we don’t want to complicate the dynamics of language, and this store typing is only for type check.

The Typing Relation

Properties

Well-Typed Stores

Extending Store Typings

Preservation, Finally

Substitution Lemma

Assignment Preserves Store Typing

Weakening for Stores

Preservation!

Progress

References and Nontermination



Testimonials

What readers say

先看读者反馈,再直接在当前页面继续讨论。公共留言需要 Waline 服务端;配置后访客只填昵称即可发布。

这类长文如果结构清楚,我会一路读到底。这里最好的地方是把概念、公式和代码示例放在同一篇里。

L
Lin 算法读者

数据库和工程文档的风格很实用,截图、SQL 和说明都能直接拿去复盘项目。

M
Mia 工程笔记党

强化学习相关文章密度很高,但排版如果更清楚,回看体验会更好。这个新版方向是对的。

R
Ryo 深夜学习者

我更喜欢能快速扫到标签、修改时间和文章重点的首页,现在这种卡片视图会比纯列表更容易选读。

C
Chen 知识整理控

代码块只要语言标识和层级做好,技术博客的专业感会立刻上来。

A
Ava 前端同行

评论区不用社交账号强绑定会更愿意留言,尤其是这种偏学习记录的网站。

N
Noah 匿名访客

Quick Identity

Pick a preset and leave a note

留言方式:先选择一个预设身份,再在下方输入评论。当前若显示“需要配置 Waline”,说明站点还缺少可写评论后端。

当前未选择预设身份

Live Discussion Waline 配置完成后,真实评论会加载在下方,移动端和主题切换会同步处理。
WALINE
Loading comments…