Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Imperative Languages

So far, we hae mostly looked at functional languages, which are descendents of the lambda calculus. For the rest of the semester, we will instead look at imperative languages. We will see that the same tools we have been using all along can equally analyze them as well. After introducing our imperative language of choice (called IMP), we will then study various techniques for analyzing IMP programs, such as noninterference (for security properties), and program logic (for correctness properties).

IMP

We now turn to analyzing a simple imperative language, called IMP, meant to model languages such as Python, Java, or C. What these languages have in common is a distinction between statements and expressions. For example, it makes sense to do the following in Python:

x = 2 + 2

But it does not make sense to do the following:

x = (x = 2 + 2)

The program x = 2 + 2 above is a statement — a thing that runs for the purpose of modifying state — while the sub-program 2 + 2 is an expression, which is only meant to compute values.

We model this abstractly by having a grammar of both statements and expressions.

\[ \begin{aligned} \text{Statements}\ s &::= x := e \mid s_1; s_2 \mid \mathsf{if}\ e\ \mathsf{then}\ s_1\ \mathsf{else}\ s_2 \mid \mathsf{while}\ e\ \mathsf{do}\ s \mid \mathsf{skip} \\ \text{Expressions}\ e &::= x \mid n \mid e_1 + e_2 \mid e_1 \times e_2 \mid e_1 - e_2 \mid e_1 / e_2 \mid e_1 \leq e_2 \\ \text{Numeric Constants}\ n &::= 0 \mid 1 \mid 2 \mid -1 \mid -2 \mid \dots \end{aligned} \]

Our statements, given by the metavariable \(s\), can either be assignment (\(x := e\)), sequencing (\(s_1 ; s_2\)), an if-then-else (\(\mathsf{if}\ e\ \mathsf{then}\ s_1\ \mathsf{else}\ s_2\)), a while loop \(\mathsf{while}\ e\ \mathsf{do}\ s\), or \(\mathsf{skip}\), which does nothing (similar to pass in Python). Our expressions, given by the variable \(e\), represent computations on integers.

For our version of IMP, we do not have Booleans explicitly, but instead encode Booleans via integers: 0 is false, and 1 is true. Hence, the control-flow statements via \(\mathsf{if}\) and \(\mathsf{while}\), by testing if the guard is \(0\) or not. The semantics of \(e_1 \leq e_2\) will return \(1\) if the value of \(e_1\) is at most the value of \(e_2\), and \(0\) otherwise.
Note that, while the rest of the operators concerning Booleans are not explicitly defined, they can be encoded:

\[ \begin{aligned} \neg e &::= 1 - e \\ e_1 \land e_2 &::= e_1 \times e_2 \\ e_1 \lor e_2 &::= \neg (\neg e_1 \land \neg e_2) \\ e_1 < e_2 &::= \neg (e_2 \leq e_1) \\ e_1 \geq e_2 &::= e_2 \leq e_1 \end{aligned} \]

For example, the following IMP program computes the \(n\)th Fibonacci number, storing the result in \(a\):

\[ \begin{aligned} &a := 0; \\ &b := 1; \\ &i := 0; \\ &\mathsf{while}\ i < n\ \mathsf{do} \\ &\quad t := a + b; \\ &\quad a := b; \\ &\quad b := t; \\ &\quad i := i + 1 \end{aligned} \]

For \(n \geq 0\), this program will terminate with the desired value stored in \(a\).

Semantics of IMP

Now, how should we specify the semantics of IMP? We will use an operational (stepping) semantics, as we have been doing before. But how to model variable assignment? We’ve seen this already: variable assignment is mutability, which we have studied for MutLang in Lecture 11! Thus, we will use the idea of a store (or a heap) which will map variables to values:

\[ \sigma : \mathsf{Var} \to \mathbb{Z} \]

To give semantics to IMP, we are going to give semantics to expressions and statements separately. Recall that for giving an operational semantics, we have two choices: a big step semantics \(\Downarrow\), which maps programs to result values, and a small step semantics \(\to\), which maps programs to other programs. It turns out that IMP can best be specified with a combination: we will use a big-step semantics for expressions, and a small-step semantics for statements.

Semantics for Expressions

First, let’s see expressions. Since expressions depend on the store, but do not change the store, the shape of our judgment will look like the following:

\[ \langle \sigma, e \rangle \Downarrow n. \]

Let’s see these rules:

\[ \dfrac{}{\langle \sigma, n \rangle \Downarrow n}\ \text{(E-Num)} \qquad \dfrac{}{\langle \sigma, x \rangle \Downarrow \sigma(x)}\ \text{(E-Var)} \]

\[ \dfrac{\langle \sigma, e_1 \rangle \Downarrow n_1 \quad \langle \sigma, e_2 \rangle \Downarrow n_2}{\langle \sigma, e_1 + e_2 \rangle \Downarrow n}\ \text{(E-Add)} \quad \text{where } n = n_1 + n_2 \]

\[ \dfrac{\langle \sigma, e_1 \rangle \Downarrow n_1 \quad \langle \sigma, e_2 \rangle \Downarrow n_2}{\langle \sigma, e_1 \times e_2 \rangle \Downarrow n}\ \text{(E-Mul)} \quad \text{where } n = n_1 \times n_2 \]

\[ \dfrac{\langle \sigma, e_1 \rangle \Downarrow n_1 \quad \langle \sigma, e_2 \rangle \Downarrow n_2}{\langle \sigma, e_1 - e_2 \rangle \Downarrow n}\ \text{(E-Sub)} \quad \text{where } n = n_1 - n_2 \]

\[ \dfrac{\langle \sigma, e_1 \rangle \Downarrow n_1 \quad \langle \sigma, e_2 \rangle \Downarrow n_2 \quad n_2 \neq 0}{\langle \sigma, e_1 / e_2 \rangle \Downarrow n}\ \text{(E-Div)} \quad \text{where } n = n_1 / n_2 \]

\[ \dfrac{\langle \sigma, e_1 \rangle \Downarrow n_1 \quad \langle \sigma, e_2 \rangle \Downarrow n_2 \quad n_1 \leq n_2}{\langle \sigma, e_1 \leq e_2 \rangle \Downarrow 1}\ \text{(E-LeqT)} \qquad \dfrac{\langle \sigma, e_1 \rangle \Downarrow n_1 \quad \langle \sigma, e_2 \rangle \Downarrow n_2 \quad n_1 > n_2}{\langle \sigma, e_1 \leq e_2 \rangle \Downarrow 0}\ \text{(E-LeqF)} \]

Note that we give a partial semantics to division: the program becomes stuck if we try to divide an expression by zero.

Semantics for Statements

Now we do statements. Since statements do modify the store, we have the small-step relation map stores and statements to stores and statements:

\[ \langle \sigma, s \rangle \to \langle \sigma’, s’ \rangle. \]

Here are the rules:

\[ \dfrac{\langle \sigma, e \rangle \Downarrow n}{\langle \sigma, x := e \rangle \to \langle \sigma[x \mapsto n], \mathsf{skip} \rangle}\ \text{(S-Assign)} \]

\[ \dfrac{\langle \sigma, s_1 \rangle \to \langle \sigma’, s_1’ \rangle}{\langle \sigma, s_1; s_2 \rangle \to \langle \sigma’, s_1’; s_2 \rangle}\ \text{(S-Seq1)} \qquad \dfrac{}{\langle \sigma, \mathsf{skip}; s_2 \rangle \to \langle \sigma, s_2 \rangle}\ \text{(S-Seq2)} \]

\[ \dfrac{\langle \sigma, e \rangle \Downarrow n \quad n \neq 0}{\langle \sigma, \mathsf{if}\ e\ \mathsf{then}\ s_1\ \mathsf{else}\ s_2 \rangle \to \langle \sigma, s_1 \rangle}\ \text{(S-IfT)} \qquad \dfrac{\langle \sigma, e \rangle \Downarrow 0}{\langle \sigma, \mathsf{if}\ e\ \mathsf{then}\ s_1\ \mathsf{else}\ s_2 \rangle \to \langle \sigma, s_2 \rangle}\ \text{(S-IfF)} \]

\[ \dfrac{}{\langle \sigma, \mathsf{while}\ e\ \mathsf{do}\ s \rangle \to \langle \sigma, \mathsf{if}\ e\ \mathsf{then}\ (s; \mathsf{while}\ e\ \mathsf{do}\ s)\ \mathsf{else}\ \mathsf{skip} \rangle}\ \text{(S-While)} \]

These rules merit some explanation. First, let’s look at (S-Assign). To evaluate \(x := e\), we first evaluate \(e\) under the big-step semantics, to get a value \(n\). We then update the store to set \(x\) equal to \(n\), and change update the statement to \(\mathsf{skip}\), which means “we are done executing”.

Now, let’s look at the sequence rules. The rule (S-Seq1) for \(s_1; s_2\) is reminiscent of the small-step rules for MutLang: we step the inner program and update the heap accordingly. The second rule (S-Seq2) says that if we are done executing on the left-hand side of a sequence, then we are done on the right-hand side. Let’s see an example, starting with the map sending every variable to zero. Below, we write \(\{x_1 \mapsto n_1, \dots, x_k \mapsto n_k\}\) for the store sending each \(x_i\) to \(n_i\) and every other variable to \(0\):

\[ \begin{aligned} \langle \{\}, x := 1; y := 2 \rangle &\to \langle \{x \mapsto 1\}, \mathsf{skip}; y := 2 \rangle && \text{(S-Seq1, S-Assign)} \\ &\to \langle \{x \mapsto 1\}, y := 2 \rangle && \text{(S-Seq2)} \\ &\to \langle \{x \mapsto 1, y \mapsto 2\}, \mathsf{skip} \rangle && \text{(S-Assign)} \end{aligned} \]

The last subtle rule is (S-While). Instead of trying to step the inner program and doing the test on the guard itself, (S-While) instead makes the observation that a while loop is equivalent to an if/then/else, where in the “then” case, we run the body once, and then recurse, and in the “else” case, we do nothing: \[ \mathsf{while}\ e\ \mathsf{do}\ s = \mathsf{if}\ e\ \mathsf{then}\ (s; \mathsf{while}\ e\ \mathsf{do}\ s)\ \mathsf{else}\ \mathsf{skip}. \]

IMP is Turing Complete (?!)

While IMP is a very simple language, in some respects — certainly conceptually simpler than System F! — a remarkable fact about IMP is that it is Turing complete. Thus, any lambda-calculus term, or C program, can be translated to an IMP program. While we won’t go into the details why exactly the essential properties that make IMP turing complete is a combination of unbounded data via integers, control flow, and loops.

Hence, even for a language as simple as IMP, there exists no algorithm that can determine basic properties for arbitrary IMP programs: for example, whether the program will terminate, or what the final value of a given variable \(x\) will be.

Adding Arrays

To make IMP more interesting, we are going to add arrays to the language. Arrays will be denoted with upper-case variables (e.g., \(T\)), and will be modeled as having an infinite size (so we don’t need to think about array access being in bounds). Like variables, we won’t have a way to create new arrays, but instead will assume the arrays we use will be held in the state. Thus, we will modify our language like so:

\[ \begin{aligned} \text{Statements}\ s &::= \dots \mid T[e] := e \\ \text{Expressions}\ e &::= \dots \mid T[e] \end{aligned} \]

To model arrays in the semantics, we need to augment our state to keep track of them. Thus, our state will now be composed of two mappings:

\[ \begin{aligned} &\sigma_\mathsf{Var} : \mathsf{Var} \to \mathbb{Z} \\ &\sigma_\mathsf{Arr} : \mathsf{Arr} \to (\mathbb{Z} \to \mathbb{Z}) \end{aligned} \]

By convention, lower-case variables (e.g., \(x\)) will be ordinary integer variables, while upper-case variables will be array variables. In the semantics, each array is mapped to an infinite array from integers to integers.

Semantics for Arrays

To extend our semantics to handle arrays, we will keep our configurations of the form \(\langle \sigma, e\rangle\) and \(\langle \sigma, s\rangle\), but will interpret \(\sigma\) here as holding two mappings internally for \(\sigma_\mathsf{Var}\) and \(\sigma_\mathsf{Arr}\). Under this notation, the original rules for IMP still apply, since we can interpret \(\sigma(x)\) to mean \(\sigma_\mathsf{Var}(x)\).

Thus, we only need two new rules for array access and array assignment. First, array access: \[ \dfrac{\langle \sigma, e\rangle \Downarrow n}{\langle \sigma, T[e] \rangle \Downarrow \sigma_\mathsf{Arr}(T)(n)} \text{(E-ArrayGet)} \]

Next, array assignment: \[ \dfrac{\langle \sigma, e_1\rangle \Downarrow n_1 \quad \langle \sigma, e_2 \rangle \Downarrow n_2} {\langle \sigma, T[e_1] := e_2 \rangle \to \langle \sigma[T[n_1] := n_2], \mathsf{skip} \rangle } \]

For array assignment, we use the notation \(\sigma[T[n_1] := n_2]\) to mean the store \(\sigma\), but modify \(\sigma_\mathsf{Arr}(T)\) so that \(T[n_1] = n_2\).

Example: Insertion Sort

Now that we have arrays, we can start to model some interesting programs. First, let’s recall the sorting algorithm insertion sort: the idea is we repeatedly process bigger and bigger prefixes of the array. For each prefix, we iterate backwards starting from the end, and repeatedly swap array elements if they are out of order. Here is insertion sort in Python:

def swap(arr, i, j):
    arr[i], arr[j] = arr[j], arr[i]

def insertion_sort(arr):
    for i in range(1, len(arr)):
        j = i
        while j > 0 and arr[j - 1] > arr[j]:
            swap(arr, j - 1, j)
            j -= 1
    return arr

To write this in IMP, we will first define \(\mathsf{swap}\) as an abbreviation for the following program:

\[ \begin{aligned} \mathsf{swap}(A, e_1, e_2) \stackrel{\mathsf{def}}{=}\ &\mathit{tmp} := A[e_1]; \\ &A[e_1] := A[e_2]; \\ &A[e_2] := \mathit{tmp} \end{aligned} \]

With this abbreviation, insertion sort is:

\[ \begin{aligned} &i := 1; \\ &\mathsf{while}\ i < n\ \mathsf{do} \\ &\quad j := i; \\ &\quad \mathsf{while}\ (0 < j) \land (A[j] < A[j - 1])\ \mathsf{do} \\ &\quad\quad \mathsf{swap}(A, j - 1, j); \\ &\quad\quad j := j - 1 \\ &\quad i := i + 1 \end{aligned} \]

In this course, we have been mostly focused on the design of functional programming languages and their type systems. In the remainder of this course, we will focus on verification: the use of concepts from PL to formally prove that programs are not only well-behaved in a generic sense (e.g., they do not get stuck), but that they are actually correct. For example, formally proving that the above program actually implements a sorting algorithm correctly.