



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




Harvard School of Engineering and Applied Sciences — CS 152: Programming Languages
The Curry-Howard isomorphism gives a connection between logic and types. This connection goes both ways: we can use insights from logic to think about programming languages, and develop new language features that correspond to logical entities; and we can use insights from programming languages influence our study and use of logic? We consider how substructural logics give rise to substructural type systems.
1.1 Natural deduction and structural inference rules
Natural deduction is a kind of proof calculus that can be used to formalize mathematical logic. It’s called “natural deduction” because it is meant to correspond to a “natural” way of reasoning about truth. In natural deduction, we write A 1 ,... , An ` B
to mean that whenever formulas A 1 through An are true, then formula B is true. For example, in a propo- sitional calculus, we may write the judgment
p, ¬q ` q ⇒ (p ⇒ r),
which intuitively means that if proposition p is true, and formula ¬q is true, then the formula q ⇒ (p ⇒ r) is true. Like we do in programming languages, we can write inference rules and axioms for a given natural deduction calculus, that define which judgments are true. For example, we may have an axiom
φ, ψ ` φ ∧ ψ
That is, if formulas φ and ψ are true, then the conjunction φ ∧ ψ is true. The inference rules that are concerned with the manipulation of the assumptions (i.e., the formulas on the left of the turnstile “`”) are known as the structural inference rules. The structural inference rules allow us to treat the assumptions like a set. That is, there are inference rules to re-order the assumptions, to collapse identical assumptions, and to remove unneeded assumptions. We use Γ and ∆ to range over (possibly empty) sequences of formulas.
There are, of course, other inference rules, depending on the logic. Here are some of the inference rules for a propositional logic. Note that the assumptions in the conclusion of the inference rules are conserved in the premises, e.g., there is no duplication or dropping of assumptions.
B ⇒ A ∆ BA ∆ BIf we drop any of the structural inference rules from the definition of our logic, we have a substructural logic. For example, if we allow Exchange but drop Weakening and Contraction we have a linear logic: every assumption must be used exactly once. If we allow both Exchange and Weakening, but drop Contraction, we have an affine logic: every assumption may be used at most once.
1.2 Substructural type systems
So, what new programming language features or designs do substructural logic give us? You may have noticed the similarity between the natural deduction judgments for logic and the type judgments we use in programming languages. A type judgment looks like
Γ ` e : τ
where we can think of the type context Γ as being a sequence x 1 : τ 1 ,... , xn : τn. Inference rules for such a type system would need to have rules for manipulating the type context.
Γ, x : τ 1 , y : τ 2 , ∆ e : τ Γ, y : τ 2 , x : τ 1 , ∆ e : τ
Γ, x : τ, x : τ, ∆ e : τ ′ Γ, x : τ, ∆ e : τ ′
WEAKENING
Γ, ∆ e : τ Γ, x : τ ′, ∆ e : τ
x not in Γ, ∆
If we drop any of these structural inference rules, we have a substructural type system.
Linear type systems So if we drop Contraction and Weakening, we have a linear type system, by analogy with a linear logic. So how does dropping Contraction and Weakening affect the set of programs that will be well typed? Well, variables placed into the typing context must be used exactly once along any control flow path. The rule Contraction would allow us to use a variable multiple times, and Weakening allows us to not use a variable at all. This makes linear type systems good for tracking the use of resources. For example, we can use a linear type system to track open file handles, and ensure that a client must always close a file (i.e., must use the file handle at least once), and cannot close a file multiple times (i.e., must use the file handle at most once). In a similar way, we can use a linear type system to track objects allocated on the heap, and (with some additional language support) ensure that we have always exactly one pointer to a heap object. This can be useful for reasoning about aliasing: if we maintain an invariant that each heap object has exactly one pointer, then if a function is given two pointers, it knows they must not alias. To use linear type systems in practice, it is often necessary to allow both linear types, and non-linear types (i.e., variables that can contraction and weakening applied to them), and/or to allow linearity to be weakened locally.
Ordered type systems Think about a type system where we drop all three structural rules (Exchange, Contraction, and Weakening). This is known as an ordered type system. Every variable is used exactly once, in the order it was introduced. In the same way that we can use a linear type system to help us reason about heap-allocated memory, we can use an ordered type system to help us reason about stack-allocated memory: not only must we use (i.e., deallocate) every piece of memory exactly once, but we must do so in stack order: i.e., the most recently allocated memory on the stack must be deallocated first.
Γ, x : un π = (Γ 1 , x : un π) ◦ (Γ 2 , x : un π)
Γ, x : lin π = (Γ 1 , x : lin π) ◦ Γ 2
Γ, x : lin π = Γ 1 ◦ (Γ 2 , x : lin π)
We also define predicates on types and contexts, to help us identify whether a type τ is a linear type (lin(τ )) or an unrestricted type (un(τ )), and whether a type context Γ consists entirely of linear types (lin(Γ)) or entirely of unrestricted types (un(Γ)). More formally:
The typing judgment has the form Γ ` e : τ , and the inference rules for the judgment are as follows.
un(Γ 1 , Γ 2 ) Γ 1 , x : τ, Γ 2 ` x : τ
un(Γ) Γ ` q b : q bool
Γ 1 e 1 : q **bool** Γ 2 e 2 : τ Γ 2 e 3 : τ Γ if e 1 then e 2 else e 3 : τ
Γ 1 e 1 : τ 1 Γ 2 e 2 : τ 2 q(τ 1 ) q(τ 2 ) Γ ` q (e 1 , e 2 ) : q (τ 1 , τ 2 )
Γ 1 e 1 : q (τ 1 × τ 2 ) Γ 2 , x : τ 1 , y : τ 2 e 2 : τ Γ ` split e 1 as x, y in e 2 : τ
q(Γ) Γ, x : τ e : τ ′ Γ q λx : τ. e : q τ → τ ′^
Γ 1 e 1 : q τ → τ ′^ Γ 2 e 2 : τ Γ ` e 1 e 2 : τ ′^
For inference rules for expressions that have subexpressions (e.g., application e 1 e 2 which has sub- expressions e 1 and e 2 ) we need to split the type context in order to type check the sub-expressions. This ensures that a linear variable is used by exactly one sub-expression. However, in the rule T-IF, we split the context into Γ 1 (which is used to type check the conditional expression e 1 ), but use Γ 2 to type check both branches e 2 and e 3. This is because execution will either e 2 or e 3. That is, no matter which branch is taken, the linear variables in Γ 2 will be used. Note that in rules T-VAR and T-BOOL, we check in the premises that the remaining variables in the context are all unrestricted. That is because those remaining variables are not used, which would be a problem if any of the variables had linear type. In rule T-PAIR, the premises q(τ 1 ) and q(τ 2 ) ensure that an unrestricted pair can not contain any linear values, enforcing invariant (2) above. Similarly, in rule T-ABS, premise un(Γ) ensures that if the function value is unrestricted (q = un), then there are no linear variables closed over in the body of the function. Consider the following example code, that attempts to discard a linear value (i.e., the linear variable x will not used when the expression is applied).
lin λx : lin bool. (lin λf : un (un bool → lin bool ). lin true) (un λy : un bool. x)
This program is not well-typed. In particular, the premise q(Γ) of T-ABS fails to hold. The following example is also not well-typed: it tries to duplicate linear values, i.e., the linear variable x will be used twice when the expression is applied.
lin λx : lin bool. (lin λf : un (un bool → lin bool ). lin (f (un true), f (un true))) (un λy : un bool. x)
Finally, note that rule T-VAR allows the variable being used, x, to appear anywhere in the type context. Because of this, we do not explicitly need an inference rule corresponding to EXCHANGE. We could, how- ever replace rule T-VAR with the following two rules, T-EXCHANGE and T-VAR2, and have an equivalent type system.
Γ 1 , y : τ ′, x : τ, Γ 2 e : τ Γ 1 , x : τ, y : τ ′, Γ 2 e : τ
un(Γ 1 ) Γ, x : τ ` x : τ
1.3.2 Operational semantics
We use a store-based semantics. That is, to emphasize the usefulness of the linear type system, we store values in the heap. (This makes sense for data structures, but for simplicity we inefficiently store all values, including boolean primitives, in the heap.) A prevalue p is either a boolean constant, a function, or a pair of values. A value v = q p is a qualified prevalue. We use a call-by-value evaluation order.
p ::= b | λx : τ. e | (v 1 , v 2 ) v ::= q p E ::= [·] | if E then e 2 else e 3 | q (E, e) | q (, E) | split E as x, y in e | E e | E
〈e, σ〉 −→ 〈e′, σ′〉 〈E[e], σ〉 −→ 〈E[e′], σ′〉
〈v, σ〉 −→ 〈, σ[ 7 → v]〉
` 6 ∈ dom(σ)
σ(`) = q true σ′^ =
σ if q = un σ \ if q = lin 〈if then e 1 else e 2 , σ〉 −→ 〈e 1 , σ′〉
σ(`) = q false σ′^ =
σ if q = un σ \ if q = lin 〈if then e 1 else e 2 , σ〉 −→ 〈e 2 , σ′〉
σ() = q ( 1 , ` 2 ) σ′^ =
σ if q = un σ \ if q = lin 〈split as x, y in e, σ〉 −→ 〈e{1 /x}{ 2 /y}, σ′〉
σ(` 1 ) = q λx : τ. e σ′^ =
σ if q = un σ \ if q = lin 〈 1 2 , σ〉 −→ 〈e{ 2 /x}, σ′〉
Rule VAL ensures that once we have evaluated an expression to a value, we allocate a new location , and put the value in the location. All the rules that use a linear value immediately free the location that they used (expressed as σ′^ = σ \, meaning that store σ′^ is the same as σ except that location ` has been removed). Otherwise, the semantics are standard. Note that the use of the linear type system ensures that a location is never accessed after it is freed.
1.4 The Rust programming language
Rust is a programming language (developed by Mozilla Research) that aims to be a memory-safe, concur- rent, and practical systems programming language. In order to ensure memory safety, Rust uses a sophis- ticated type system to reason about the lifetime of data. This ensures that memory can be efficiently freed as soon as it is no longer needed (without the need for a garbage collector), also that pointers to data are handled correctly, including not dereferencing freed memory (no use-after-free) and pointers are not used to free memory multiple times (no double-free).
to. This is good! It means that we can automatically and efficiently recover the memory resources, without the programmer needing to worry about explicitly freeing memory. Ownership can move from one variable to another, permanently or temporarily. If ownership is moved temporarily, it is called borrowing. In the following example, ownership of the vector object is transferred from v to w, and, once a goes out of scope, it is transferred back to v.
let mut v = vec![20,21,22]; { let a = &mut v; a.push(23); println!("The answer is {}", a[3]); } // ownership is now back with v v.push(24); The Rust type system enforces two invariants:
let mut a = &mut vec![0]; { let mut v = vec![20,21,22]; let a = &mut v; a.push(23); } // vector object is deallocated here
println!("The answer is {}", a[3]); // ERROR: use after free, // since a outlives v The second invariant in primarily useful to ensure safety in concurrent settings (and we will consider concurrency in later lectures). However, note that it is completely fine to have multiple immutable refer- ences to the same object! In the following example, one mutable reference to the object is borrowed by multiple immutable references.
let mut v = vec![20,21,22]; { let a = &v; // immutable reference to v let b = &v; // immutable reference to v
// ownership of v is now shared between a and b
println!("The answer is {}", a[0] + b[2]); } // ownership is now back with v // we can use v to update the object. v.push(24);
Rust includes many more features beyond those we’ve had space to discuss here. More information about Rust is available at https://www.rust-lang.org/. Extensive pointers to resources for learn- ing Rust are at https://github.com/ctjhoa/rust-learning. For the material covered in this lec- ture, the Chapter 4 (Ownership and Lifetimes) of The Rustonomicon is most relevant (see https://doc. rust-lang.org/nomicon/ownership.html).