CComputer Science, Built

Act XI · The Research Frontier

Part 58 of 61

Semantics

Researchstarts at this level52 min of film13 chaptersprerequisites: Part 13, Part 14, Part 15, Part 54

What does a program mean, and when do two programs mean the same thing?

The part opens with three meanings of factorial: as steps (the small-step interpreter rewrites fact 3 down to 6 in 18 steps), as a limit (a chain of partial functions) and as laws. One small call-by-value language with recursion is given Plotkin's small-step rules, Kahn's big-step rules and a CEK machine, and the three agree on 300 of 300 random programs. Scott and Strachey's denotational semantics then gives each construct one equation, and recursion becomes the least fixed point of a continuous functional on a complete partial order, computed as the Kleene chain whose k-th member is factorial on 0 to k - 1. Soundness and adequacy tie the steps to the mathematics by a logical relation; the turn is full abstraction, which fails for PCF because parallel-or is continuous but not sequential. The same tools decide when programs are equal (bisimulation tells a.(b + c) from a.b + a.c although their traces agree), read theorems off types (Reynolds's and Wadler's parametricity, tested on random lists, with the counterexample for sort under squaring), and prove Hoare logic sound. The part ends by stretching meaning to effects as monads and handlers, dependent types, and CCS and the pi-calculus, and at the frontier with mechanized semantics of C, ML and WebAssembly, homotopy type theory, and a memory model for C that is still open.

What you need. Proof by induction on derivations, partial orders and least upper bounds; some experience with a functional language helps.

Mathematics, ideas and history
operational and denotational semantics, domain theory and Scott's D∞, PCF and full abstraction, logical relations, parametricity, monads and effects, π-calculus
What we build or compute
three interpreters that agree; free theorems checked

What you will be able to do

Degree

  • Evaluate a small program by the small-step rules, naming the search or reduction rule used at each step.
  • Compute the first Kleene iterates of the factorial functional and say on which inputs each is defined.

Graduate

  • Prove that small-step evaluation is deterministic, by induction on derivations.
  • Prove Kleene's fixed-point theorem, and show that the factorial functional is continuous and that its least fixed point is factorial.
  • Derive the free theorem for a function of type forall a. [a] -> [a] from the relational reading of types.

Research

  • Prove adequacy for a language with fix by a logical relation, handling fix through the Kleene chain and admissibility.
  • Explain with parallel-or why Scott's model is not fully abstract for PCF, and what game semantics changes.
  • State the out-of-thin-air problem and what an accepted relaxed-memory semantics for C would have to forbid, permit and compile to.

Industry

  • Test two implementations of a language against each other on random terminating programs, and say what agreement does and does not show.
  • Use a free theorem as a property test or a fusion rule, and say where seq, run-time type tests and general recursion weaken it.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Degree 14 min · Graduate 19 min · Research 52 min · Industry 19 min.

  1. 0What does a program mean?Degree2 min
  2. 1Meaning as stepsDegree5 min
  3. 2Meaning as mathematicsDegree5 min
  4. 3Domains and fixed pointsResearch4 min
  5. 4Adequacy and full abstractionResearch4 min
  6. 5When are two programs the same?Research4 min
  7. 6Theorems for freeResearch5 min
  8. 7Hoare logic, proved soundResearch4 min
  9. 8Effects and monadsIndustry5 min
  10. 9Dependent typesResearch5 min
  11. 10Processes and channelsResearch5 min
  12. 11Frontier: semantics of real languagesResearch1 min
  13. Recap, problems, and where this comes backAll tracks2 min

Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.

What does a program mean?Degree2 min

What does a program mean? Here is factorial, and three different answers. First, as steps: the meaning is what a machine does with it. Our interpreter rewrites fact of three in 18 small steps, down to six. Second, as a mathematical object: the meaning is a function, the limit of a chain of approximations. The first knows nothing, the next knows factorial of zero, the next of zero and one, and the limit is factorial itself. Third, as laws: the meaning is what can be proved about it, equations and Hoare triples. These are operational, denotational and axiomatic semantics, and the deep results of this part say when they agree.

Why does this matter outside a classroom? A compiler is correct exactly when the meaning of what it emits equals the meaning of what it was given, which is how CompCert was proved. A refactoring is safe when no surrounding program can tell the old code from the new. And languages can be designed with their meaning written down first: WebAssembly's specification was formal before the language shipped. In this part we build three interpreters for one small language and check that they agree, on 300 of 300 random programs we tried; then we prove why.

1Meaning as stepsDegree5 min

What does a machine do with a program? We need a language small enough to reason about and large enough to be interesting. Its terms are integers and booleans, variables, functions and their applications, conditionals and arithmetic, and one construct for recursion: fix f x arrow e is a function named f, of argument x, whose body may call f itself. Some terms are finished: numbers, booleans and functions. These are the values, and a program's whole job is to become one. Here is factorial, written with fix. We follow it through this whole part.

Gordon Plotkin's structural operational semantics, from his Aarhus lecture notes of nineteen eighty-one, defines one step of computation by rules: above the line, what must hold; below it, what follows. Search rules say where to look. To step an arithmetic term, step its left side; once that is a value, step the right. That is call by value, left to right, made explicit. Reduction rules say what to do when the search finds something ready. Two numbers become their sum or product; a conditional on true becomes its first branch; a function applied to a value becomes its body, with the value substituted for the parameter. And fix unrolls itself: the body receives the value for x, and the whole function for f.

Each step is a small theorem, with a proof tree. Here is the step our interpreter takes from the fourth term of factorial's trace to the fifth: three times fact of three minus one becomes three times fact of two. Read the tree from the bottom. Three is a value, so the product may step its right side. Fact is a value, so the application may step its argument. And three minus one steps to two, by arithmetic. A first theorem: if a term steps to e one and to e two, then they are equal. The language is deterministic. The proof is an induction on the derivation: values never step, and every search rule needs everything to its left to be a value, so at most one rule ever fits.

Here is factorial of three, from our small-step interpreter, one step at a time, with each step's new piece in yellow. Watch the length of the term. It grows as multiplications pile up, each waiting for its right-hand side: three times, two times, one times. Those pending operations are the call stack of Part 11, written into the term itself. At the base case the term collapses, and after 18 steps it is the value 6. Because the language is deterministic, a run is a line, not a tree, and the value at its end, if there is one, is what the program means.

Small steps answer the question: what happens next? Sometimes we only want the answer. Gilles Kahn's natural semantics, from nineteen eighty-seven, relates a term directly to its value: e evaluates to v. A value evaluates to itself; an arithmetic term evaluates both sides and combines them; an application evaluates the function, then the argument, then the body with the argument substituted. Now the proof tree is the whole computation. Squaring, applied to one plus two: the function is a value, the argument evaluates to three, and the body, three times three, to nine. The two semantics agree: e evaluates to v exactly when e reaches v in small steps. Our big-step evaluator uses environments instead of substitution, and it agrees with the small-step interpreter on 300 of 300 random programs.

Neither semantics is how a real interpreter runs. Matthias Felleisen and Daniel Friedman's CEK machine, from nineteen eighty-six, keeps three registers: a control term, an environment for the variables, and a continuation, a stack of frames saying what to do with the next value. Here it runs a function applied to two. It remembers the argument in a frame, evaluates the function to a closure, then the argument, binds x to two, and works through x plus one with two more frames. Each transition does constant work, so it takes more of them: about two hundred and ninety-four per program on average, against seventy-three small steps. But each small step searches and copies the whole term. This is the interpreter loop of Part 15, derived from the rules.

2Meaning as mathematicsDegree5 min

What object does a program stand for? Operational semantics says what a machine does with a program. Denotational semantics, begun by Dana Scott and Christopher Strachey at Oxford in their paper of nineteen seventy-one, asks instead what a program is. Each term is mapped, by the semantic brackets, to a mathematical object called its denotation. The term fun x arrow x times x denotes the squaring function on the integers: a set of pairs, and nothing more. A different program, x times x plus zero, takes more steps, and denotes exactly the same function. So the denotation keeps what is computed and forgets how. That is precisely what we need before we can say that two programs are interchangeable.

There is one equation for each construct, and the environment, rho, supplies the values of the free variables. A numeral means its number. A variable means what the environment says. An arithmetic term means the operation applied to the meanings of its sides; a conditional means one branch or the other, by the meaning of its condition. A function means a mathematical function: given v, the meaning of its body with x bound to v. An application means the function's meaning applied to the argument's. A term that never finishes means bottom, the undefined element, and bottom spreads through every operation. Notice that each right-hand side mentions only the meanings of the parts. This is compositionality: meaning is assembled from the leaves up, with no machine and no order of steps. One construct is missing, and it is the interesting one: fix.

Let us compute one meaning by nothing but equations. Squaring, applied to one plus two. By the application equation, its meaning is the meaning of the function applied to the meaning of the argument. The function means the map taking v to the meaning of x times x with x bound to v; and one plus two means three. Apply the map: the meaning of x times x, with x bound to three. And that is three times three, nine. The big-step tree of chapter one reached the same nine by evaluating. Here there was no evaluation at all, only algebra, and each line followed from the one before by replacing equals by equals, the way we simplify any expression in school.

Compositionality pays for itself at once. Take any program with a hole in it. This is called a context. Plug in two terms with the same meaning, and the whole programs have the same meaning, whatever the context is. The proof is an induction on the context, and it goes through because every equation looks only at the meanings of the parts. This is what licenses an optimizer, like Part 13's, to replace x times x plus zero by x times x anywhere in a program: one local fact about meanings, used everywhere. Whether the converse holds, whether programs that no context can tell apart always have equal meanings, is the question of chapter four.

Recursion is where the mathematics has to work. The meaning of fix f x arrow e should be a function g that satisfies its own definition: the map from v to the meaning of the body, with f bound to g itself. Write the right-hand side as a functional F, which takes a candidate h to an improved one. Then g equals F of g: a recursive function means a fixed point of F. For factorial, F of h, at n, is one if n is zero, and n times h of n minus one otherwise. But an equation can have several solutions. Both of these are fixed points of factorial's F: they agree on the naturals, and on negative numbers one is undefined while the other is zero. Which is the meaning? Run fact on minus one, and it calls itself on minus two, minus three, forever. So the answer there is undefined: the least defined fixed point. Making least precise, and proving that it always exists, is domain theory, the next chapter.

3Domains and fixed pointsResearch4 min

Why does every recursive definition have a meaning? To choose the least solution we need an order, and Dana Scott's insight was to order meanings by information. In the integers with bottom, the undefined result sits below every number, and the numbers sit side by side: knowing that a result is three is neither more nor less than knowing that it is four. Functions are ordered pointwise: one is below another if, wherever the first is defined, the second is defined too, and agrees. Filling in answers moves up the order. Changing an answer does not: h has more answers than f, but it is not above f.

Domains are partial orders with two extra properties. There is a least element, bottom: no information at all. And every chain, each element at least as defined as the one before, has a least upper bound: above them all, and below every other bound. This is a complete partial order, a cpo. In the integers, chains climb at most one step. But among partial functions a chain can climb forever, and its least upper bound collects all of their answers. That is how an infinite object, like factorial on all the naturals, is reached from finite pieces.

Kleene's theorem needs two properties of F. It must be monotone: more information in gives at least as much out. And it must be continuous, in Scott's sense: F of the limit of a chain is the limit of F along the chain. Any finite part of the output depends on only a finite part of the input. Here is a monotone function that is not continuous. H returns one if its argument is a total function, and bottom otherwise. Along the chain of partial factorials every answer is bottom, so the limit is bottom; but H of the limit is one. No program computes H: it would decide whether a function halts everywhere, a cousin of Part 25's halting problem.

Now the theorem, usually credited to Stephen Kleene. If D is a cpo and F is continuous, then the limit of bottom, F of bottom, F of F of bottom, and so on, is the least fixed point of F. First, a chain: bottom is below F of bottom, since bottom is below everything; apply the monotone F n times. Second, a fixed point. Apply F to the limit. By continuity, F passes inside. F of F to the n is F to the n plus one: the same chain with bottom missing from the front, so the same limit. Third, the least: by induction, every element of the chain is below any fixed point d, so their least upper bound is too. It is the climb of Part 13's liveness analysis; here it may go on forever, and continuity carries us to the limit.

Here is the theorem at work, computed by our instrument. Start with bottom, the function that knows nothing. Apply factorial's F once, and it knows that factorial of zero is one. Again, and it knows zero and one. Each application adds one answer. So the k-th function is factorial unrolled k times: it answers every input that needs fewer than k recursive calls. The chain never stops, but its least upper bound is the whole of factorial, the least fixed point that chapter two was looking for, still undefined on negative numbers. A while loop works the same way: its meaning is the least fixed point of one unrolling, and the k-th approximation runs the loop at most k times.

4Adequacy and full abstractionResearch4 min

Do the steps and the mathematics agree? We now have two meanings for every program: the steps of chapter one, and the mathematics of chapters two and three. Do they agree? Soundness: if a program steps to a value, its denotation is the denotation of that value. Computing never changes meaning. Adequacy: if the denotation of a whole program of integer type is a number n, not bottom, then the machine really does reach n. Together, the mathematics predicts exactly what the machine does, including whether it stops. Gordon Plotkin proved this in nineteen seventy-seven for PCF, a typed lambda calculus with numbers, booleans and fix: essentially our language, with types.

Soundness is the easy direction: show that one step preserves meaning, then count the steps. Take the beta rule, a function applied to a value. By the equations, its meaning is the map, applied to the value's meaning. Applying the map binds x to that meaning. And by a substitution lemma, proved by induction on e, that is the meaning of the body with the value substituted. The fix rule works the same way, and it is exactly where we need fix to mean a fixed point. Adequacy is harder. Try induction on the program. At an application, all we know is that the function's meaning is some mathematical function, and a hypothesis about integers says nothing about the function program. We need a statement about every type at once.

That statement is a logical relation: one relation for each type, each built on smaller types, like the rungs of a ladder. On the bottom rung, the integers: a meaning d is related to a program e if d is bottom, or e evaluates to d. On the rung for functions from sigma to tau, d is related to e if d is bottom, or e evaluates to a function value v, and whenever a meaning a is related to an argument program, d of a is related to v applied to that program. Related arguments go to related results. Each rung uses only smaller types, so the definition is well founded; that is why the language must be typed.

The fundamental lemma: every well-typed closed program is related to its own meaning. The hard case is fix, whose meaning is the limit of a Kleene chain, here factorial's. Bottom is related to anything, by definition. If one approximation is related to the program, so is the next, because one more unrolling of the meaning matches one more use of the fix rule. And each relation is closed under limits of chains, a property called admissibility, so the limit, the meaning itself, is related. Now read the lemma at type int. If the meaning of e is a number n, then n is related to e, which, on the bottom rung, means that e evaluates to n. That is adequacy.

Two programs are contextually equivalent when no context can tell them apart. If two terms have the same meaning, then by compositionality every context gives them the same meaning, and by adequacy the same behaviour. Full abstraction is the converse: equivalent programs have equal meanings, so the model sees no distinction that programs cannot. Plotkin showed that Scott's model of PCF is not fully abstract. The culprit is parallel-or: true if either argument is true, even when the other runs forever. It is continuous, so it lives in the model, but no PCF program computes it. A sequential program must look at one argument first, and if that one loops, so does the program. So two tests that differ only on parallel-or are equivalent in PCF, though their meanings differ. And adding parallel-or to the language, Plotkin showed, makes the model fully abstract.

5When are two programs the same?Research4 min

Can we prove it without trying every context? Chapter four defined sameness: two programs are contextually equivalent when no context can tell them apart. Are x plus x and two times x the same function? Apply each to five, add one to its value at three, apply it twice: every test agrees. But there are infinitely many contexts, and testing is not proof. This chapter gives two methods that never quantify over contexts: bisimulation, which checks one step and then the same again, forever; and logical relations, which build sameness type by type.

Programs that run forever are better compared by what they can do next. Here are two tiny machines in Milner's notation. Both can do a then b, or a then c: the same traces. But read a as a coin, and b and c as tea and coffee. The first takes your coin and lets you choose; the second chooses for you as it takes the coin.

Bisimulation makes this a game. An attacker moves in either machine: a coin, in the first. The defender must answer with the same action in the other, and so commits to a branch. Whichever it picks, the attacker asks for the drink that branch cannot give. The attacker always wins, so the machines are not bisimilar, and one formula says why: the first can take a coin and then offer both drinks.

The definition is David Park's, from nineteen eighty-one, refining Robin Milner's work on CCS. A relation is a bisimulation if, whenever p is related to q, every move of p is matched by a move of q with the same action, into related states, and the other way round. Write F of R for the pairs whose moves match into R. Bisimilarity is the union of all bisimulations, the greatest fixed point of F, by Knaster and Tarski. Chapter three climbed to least fixed points from below; this one is reached from above. Its proof principle is coinduction: exhibit one relation, and check one step.

Here coinduction proves two machines the same. V takes a coin and serves tea or coffee, then starts again. W does the same, but returns to a copy of its start. Exhibit a relation: the starts together, the waiting states together, and V's start with W's copy. Check one step for each pair: every move lands in a related pair. So the machines are bisimilar, forever, from a finite check. Our checker finds such relations itself, starting with everything related and splitting blocks until nothing changes.

For functions, Samson Abramsky's applicative bisimulation, from nineteen ninety, plays the same game. If one program evaluates to a number, the other must give the same number; if to a function, so must the other, and the two bodies, given any one argument, must be related again. Our two functions are already values. Apply both to the same n. Substitute. Both give two n. One argument at a time, never a context. By Howe's method this relation is a congruence, so in a pure language like ours it coincides with contextual equivalence.

The second method builds sameness by induction on types: chapter four's ladder, now between two programs. Integer programs are related if they give the same number, or both diverge. Functions are related if they send related arguments to related results. The fundamental property, by induction on typing: every well-typed program is related to itself. Now take two related programs. Put both in a context: applied to the context, the fundamental property keeps them related. On the bottom rung, that means the same result. For every context: contextual equivalence, with no context examined.

6Theorems for freeResearch5 min

What does a type promise about every program of that type? John Reynolds asked what it means for a type to hide something. Here are two counters. One counts up from zero; the other counts down, and reads its state negated. A client sees the state only through start, increment and read. Relate n in the first to minus n in the second. The starts are related, increment keeps related states related, and read gives equal numbers. Reynolds' abstraction theorem, of nineteen eighty-three, says that then no client that is polymorphic in the hidden type can tell the two apart. In his words, type structure is a syntactic discipline for enforcing levels of abstraction.

The idea behind the theorem is chapter five's ladder again, with one new rung. Read every type as a relation. Integers are related when they are equal. Functions are related when they send related arguments to related results. Lists are related when they have the same length and are related element by element. And the new rung: a polymorphic value is related to another if, for every pair of types and every relation between them, its two instances are related. The abstraction theorem: every well-typed term is related to itself, at its own type. A polymorphic function cannot inspect its argument, so it must respect every relation at once.

Now read off a theorem. Take any function r from lists of a to lists of a. By the abstraction theorem, r is related to itself at its type. By the for-all rung, for any types A and B and any relation R between them, the instances of r are related at lists of R to lists of R. By the function rung: related lists go to related lists. Now the one creative step: choose R to be the graph of a function f. Lists are related exactly when mapping f over the first gives the second. Take ys to be map f of xs. And there it is: map f after r equals r after map f, for every f, and every r of this type, without reading a line of r's code.

Draw the theorem as a square. Start with a list, reverse it, then square every element; or square first and reverse after. Both paths meet. Our property test tries four rearrangements, reverse, take three, every other element and rotate, on random lists, with random quadratic functions f. The law held every time. In Part fourteen we tested linear functions only; the derivation shows why that was never needed. The theorem asks nothing of f at all.

Wadler's paper of nineteen eighty-nine turned this into a method: write down a type, and read off its theorem. Take sort, which is given a comparison. Its type says that related comparisons give related sorts. With R the graph of f, the comparisons are related when comparing x and y gives the same answer as comparing f of x and f of y. So for an f that preserves and reflects the order, mapping and sorting commute. The condition matters. Our test found this list for squaring, which is not monotone: minus fifteen is below minus six, but its square is larger. Sort, then square, and the list is out of order; square, then sort, and it is sorted. For two x plus one, the law held on every list.

Free theorems hold only while the language keeps its side of the bargain. This Java method has the type of the identity, but it tests the type of its argument at run time and returns something else for strings. The free theorem says it must be the identity, and it is not. General recursion bends the theorems too: every type now contains bottom, and Wadler showed they then need f to be strict. Haskell's seq, which can tell bottom from a function, bends them further. Where the bargain holds, it pays. GHC fuses list pipelines with a rewrite rule, foldr of build, whose correctness is a free theorem, and modules can swap their hidden representations safely, as Reynolds' counters did.

7Hoare logic, proved soundResearch4 min

Why should we believe the rules? Part fifty-four used Hoare's rules to prove programs correct. But the rules are symbols on paper. Why believe them? A triple can be derivable: built from the rules, like this sequence of two assignments. Or it can be true: every run of the program that starts in a state satisfying P, and ends, ends in a state satisfying Q. Truth is defined by the operational semantics, the steps of chapter one, now for commands. Soundness says every derivable triple is true. And Stephen Cook showed in nineteen seventy-eight the converse, with a precise proviso we will come to: every true triple is derivable.

First, the meaning of commands, in big steps. A state, sigma, gives every variable a value. Assignment updates one variable. A sequence runs the first command, then the second from where the first left off. A loop whose test is false stops at once. A loop whose test is true runs its body once, then runs the whole loop again. Notice that the loop reappears in its own premise. A proof about loops cannot go by induction on the program, which does not shrink; it goes by induction on the derivation of the run, which does.

Soundness is proved by induction on the derivation of the triple, one case per rule. Assignment first, the rule that runs backwards. Suppose the state satisfies Q with e put in place of x. That is, the assertion evaluates to true in sigma. A substitution lemma, proved by induction on the assertion, moves the substitution into the state: Q is true once x is updated to the value of e. So the updated state satisfies Q. And by the assignment rule that updated state is the only possible final state. Sequencing chains the two hypotheses through the middle state, and consequence is pure logic.

The loop rule is the heart of the proof. Our outer hypothesis: the body, started with the invariant and the test true, keeps the invariant. We must show the loop keeps it, and leaves with the test false. Take factorial as a loop, with invariant: x is not negative, and y times x factorial is three factorial. Run it from x equals three. Each pass of the body starts with the test true and the invariant holding, so the outer hypothesis gives the invariant again. When the test fails, the loop stops, with the invariant and not the test: y is six. The proof does the same by an inner induction, on the derivation of the loop's run. If the loop stopped at once, the invariant still holds. Otherwise the body keeps it, and the rest of the run has a shorter derivation.

Now the converse. Cook's idea is to use the weakest liberal precondition: the states from which the command either ends in Q, or runs forever. By induction on the command, the triple with wlp in front is derivable. In the while case, the invariant nobody had to invent is the loop's wlp itself, and both premises of the loop rule are true. A true triple means P implies the wlp, so consequence finishes the proof. Why only relative? A true triple with skip is just a true statement of arithmetic, and by Gödel no proof system lists them all. So Cook assumes the true assertions are given, and that assertions can express wlp. Part fifty-four's tools discharge exactly those assertions; this chapter is why their rules are right.

8Effects and monadsIndustry5 min

How can a mathematical meaning describe a program that does things? Every meaning so far was pure: an integer expression denoted an integer. Real programs do more. Twelve divided by b may fail. A counter may be read and changed. A choice may give several answers. None of these denotes one number. Failure needs an extra value; state needs a function from the old counter to a result and a new one; choice needs a list. Eugenio Moggi, in nineteen eighty-nine and nineteen ninety-one, said this uniformly: tell values apart from computations, and let a computation of an integer mean an element of T of the integers, for a structure T called a monad. Each effect is a choice of T.

A monad is three things. A type constructor T, and return, which turns a value into a computation that does nothing else. And bind, which runs a computation of an A and feeds its value to a function that produces a computation of a B. Think of a program as a pipeline of stages, each taking a plain value and producing a computation. Bind is the joint between stages: it unpacks what one stage produced and feeds the next, and the effect lives entirely in the joints. Philip Wadler's papers of nineteen ninety-two carried this into programming. A do block in Haskell is bind, written sideways.

Three monads, one shape of program. For exceptions, T of A is an A or Nothing, and bind skips the rest once a stage has failed. Twelve divided by zero gives Nothing; by three, five after adding one; by four, four. For state, T of A is a function from the counter to a result and a new counter, and bind threads the counter through. Tick twice from zero, then return ten times the counter: twenty, with the counter left at two. For nondeterminism, T of A is a list, and bind runs the rest once for each possibility. Choosing b from one to four gives twelve, six, four and three. Only the joint changed.

A monad must obey three laws, which make sequencing behave. Left unit: returning a value and binding it is just applying the next stage. Right unit: binding to return changes nothing. Associativity: how you group a pipeline does not matter. Check the first law for state, by algebra, as in chapter two. Unfold bind: a function of the counter that runs return a, and passes its result and new counter to k. Return a, given s, is the pair a and s. So x is a, and s prime is s. And a function that applies k a to its argument is k a itself. The law holds; the other two are checked the same way.

There is a tidier way to state the laws. Compose two effectful functions, f from A to computations of B and g from B to computations of C, by running f and binding its result to g. This is Kleisli composition, after Heinrich Kleisli. Take the left unit law, rewrite it with the new composition, and drop the a: return composed with f is f. Likewise f composed with return is f, and composition is associative. Effectful functions form a category, with return as its identity. And this is Moggi's semantics: a program with a free variable of type A and a result of type B denotes a Kleisli arrow, and let is bind.

Gordon Plotkin and John Power, in two thousand and one, started from the other end: an effect is given by its operations. Here, choose, which returns a boolean, and fail, which never returns. A program using them is a tree: a node per operation, a branch per answer, values at the leaves. Matija Pretnar and Plotkin added handlers in two thousand and nine. A handler says what each operation does, given the rest of the program as a continuation, and running the program folds the tree. One handler collects every result: six and four. Another backtracks: try true, and only if that fails, try false. Same tree: six. The program never changed, only its handler. OCaml five builds its effects this way; exceptions, generators and async code can all be written as handlers.

9Dependent typesResearch5 min

What if types could mention values, and proofs were programs? Part 14 gave a first glimpse of types that mention values; here is how far the idea goes. Picture a family of types, one for each x in A, each a column above its point. A dependent function picks an element from every column, so its result type depends on its argument. Its type is a capital pi. When B does not mention x, every column is the same, and pi is the ordinary arrow. A dependent pair is one point in one column: a value x, and an element of B of x. Its type is a capital sigma, and when B is constant, the ordinary product. Per Martin-Löf's type theory, begun in nineteen seventy-two, is built on these two.

Part 14's example, now in full: a list that carries its length in its type. Vec A n is the type of lists of exactly n elements of A. nil has length zero, and cons, on a vector of length n, gives length n plus one. Now head can demand a vector of length n plus one, and append, given lengths m and n, returns length m plus n. Append seven and two to five. The checker computes the type: two plus one, which is three. And head of the empty vector is not a crash at run time, as in most languages; it is rejected before the program runs, because no n plus one equals zero.

Part 14 met the Curry–Howard correspondence. A proof of A and B is a pair, a proof of A or B is a tagged proof of one, a proof that A implies B is a function, and falsehood is the empty type. For all x, P of x, is a dependent function: a proof for every x. There exists an x with P of x is a dependent pair: a witness, and a proof about it. And equality is a type, whose one constructor, refl, proves that a value equals itself. For every n there is a larger m: the proof is a function returning n plus one, with a proof that it is larger. A proof is a program, and checking it is type checking.

Some theorems are proved by computing. Define addition by recursion on its first argument: zero plus n is n, and the successor of m, plus n, is the successor of m plus n. Claim: two plus two equals four, and the proof is refl, which proves that a thing equals itself. Because the checker computes. Two plus two is the successor of one plus two, which is the successor of the successor of zero plus two, which is two with two successors, four. Both sides reach the same normal form. But n plus zero does not compute: addition looks at its first argument, and n is a variable. Its proof is a recursive function, whose second case calls itself on a smaller n. Induction is recursion.

Type checking must decide when two types are equal. Meeting a vector of length two plus one where it expects length three, it normalizes both and compares. That works only if normalizing always stops. Allow one looping definition, bad equals bad, and it has any type, even falsehood: the logic would prove everything, and checking would run forever. So proof assistants accept only functions they can see terminate, such as recursion on a structurally smaller argument. That every well-typed term has a normal form is proved with chapter five's method, Tait's, which Jean-Yves Girard extended to polymorphism in nineteen seventy-two. Martin-Löf's nineteen eighty-four theory, with extensional equality, makes type checking undecidable; the intensional version keeps it decidable.

This is why a proof assistant can be trusted. Thierry Coquand and Gérard Huet's calculus of constructions, of nineteen eighty-eight, became the core of the Coq proof assistant, later extended with inductive types. Around the core sits a large, clever, untrusted layer: tactics, automation, and an elaborator that fills in what the user leaves out. Its only output is a proof term. The kernel, a small type checker, checks that term, and only the kernel has to be right. It is the idea of Part 54's small trusted kernel again, and a kernel like this one checks the proof of Part 54's verified compiler, CompCert.

10Processes and channelsResearch5 min

What does a program mean when it talks to others? Chapter five compared machines; now we build them from parts. Robin Milner's Calculus of Communicating Systems, of nineteen eighty, has a tiny grammar. An action is a name a, its complement a bar, or tau, a silent internal step. A process is zero, which does nothing; an action followed by a process; a choice; two processes in parallel; a restriction, which makes a name private; or a named process, which may call itself. A customer offers a coin, then waits for tea. A machine accepts a coin, offers tea, and starts again. Side by side, complementary ports join, and restriction hides both names from everyone else. Tony Hoare's CSP, of nineteen seventy-eight, also built programs from processes that exchange synchronous messages; Go's channels descend from it.

The meaning of a process is a labelled transition system, given by rules in the style of chapter one. An action prefix can do its action and become the rest. A choice can do whatever either side can, and the other side is dropped. In parallel, either side may move alone, the other unchanged. The heart is communication: if one side can do a and the other a bar, together they take a silent tau step, both moving at once. And a restricted name cannot be used from outside: a move on a or a bar is blocked, but tau passes through. These five rules, with their mirror images and one for unfolding named processes, are all of CCS.

Let us derive the customer's first step. By the action rule, the customer, unfolded, can do coin bar and become tea, then zero. The machine can do coin and become tea bar, then V. The communication rule joins them: together they take a tau step to the two remainders. Restriction lets tau through, so the closed system moves. Every step of a system is a small proof like this one. The closed system has just two tau steps, coin and then tea, after which nothing more can happen. Chapter five's bisimulation applies, with tau steps treated as unobservable: Milner's weak bisimulation. Seen from outside, this system is equivalent to zero. And strong bisimilarity is preserved by every operator of CCS, so equal parts can be swapped inside any system.

In CCS the wiring is fixed: who can talk to whom never changes. The pi-calculus of Milner, Joachim Parrow and David Walker, from nineteen ninety-two, sends names over names. Send y on channel x; receive a name on x and call it z. When they meet, the receiver continues with y in place of z. Now a server makes a private channel r, and wants to send it to a client over the public channel s. First, the scope of r is widened to include the client, which is allowed because the client does not mention r. Then the message passes, and the client holds r. The scope has extruded: the two now share a private link that no one else can reach. Links between processes are data. A request that carries its own reply channel, as in Go, is exactly this.

Concurrency's classic failure is now a precise question. A lock, as in Part 33, is a process that can be grabbed, then released, forever. Thread one grabs lock a, then b, then releases both; thread two grabs b, then a. Draw each state of the closed system as a point: how far thread one has got, across, and thread two, up. Every grab and release is a tau step. Where both threads would hold one lock, there is no state. Explore from the start: nineteen states are reachable. Two have no move. One is the finish. The other is deadlock: each thread holds one lock and waits for the other's. A deadlock is a reachable stuck state that is not finished, and finding one is a search, which is what Part 54's model checker does. Session types go further: a channel's type is its protocol, like Part 43's request and reply, and some type systems built on them rule out such deadlocks before the program runs.

11Frontier: semantics of real languagesResearch1 min

Can a whole real language be given a meaning that a machine can check?

For decades semantics was done on paper, for small languages. Then Xavier Leroy's CompCert gave a large subset of C a semantics in the Coq proof assistant, and proved that its compiler preserves it. CakeML did the same for a dialect of ML, with a verified compiler that compiles itself. And WebAssembly was specified by small-step rules like chapter one's from its first version, with its type system later proved sound in Isabelle. Still missing are a full semantics of C's concurrency, the out-of-thin-air problem of Part 33, and almost every language people actually write.

The deepest frontier is about equality itself. In Martin-Löf's type theory, the basis of chapter nine's dependent types, a proof that a equals b is itself a value, of a type. Vladimir Voevodsky's univalence axiom says that equivalent types are equal, which is how mathematicians already reason. The model that makes sense of it reads equalities as paths in a space, and two paths between the same points need not be the same path. This is homotopy type theory, and cubical type theory, a few years later, made univalence compute.

Recap, problems, and where this comes backAll tracks2 min

What we built in this part. Three operational semantics for one language, small-step, big-step and the CEK machine, agreeing on every program we tried. A denotational semantics, where recursion is a least fixed point reached by Kleene's chain. Adequacy and full abstraction, and the parallel-or that PCF cannot define. Equivalence by bisimulation and logical relations, and the normalization proof they give. Parametricity's free theorems; Hoare logic proved sound; effects as monads; dependent types; and processes that communicate. One idea runs through it: meaning is compositional, the meaning of a whole is built from the meanings of its parts.

Where this comes back. Part 59's distributed algorithms are processes like chapter ten's. Part 60 describes hardware as programs whose meaning must match a specification. Part 61 treats proof as a research method. And looking back, Part 54's verification and Part 55's trusted compilers both rest on the semantics of this part.

In practice. Write a language's rules down before implementing it. Use two interpreters that must agree as a test oracle for each other. Justify a refactoring by an equivalence, not by hope. Put effects in the types, so that errors, state and asynchrony are explicit. And when the stakes justify it, mechanize the semantics.

Six problems, with full solutions in the part's notes. Pause on any of them. The fifth is a build problem: add exceptions to all three of our interpreters and check that they still agree. The last, marked with a star, is a research problem: a memory model for C that forbids values from thin air and still lets compilers optimize.

Next time, Part 59: the theory of distributed computing. What can n processes compute when each sees only its neighbours, or some crash, or some lie? Some answers are lower bounds as sharp as log star of n, and one of them came from algebraic topology.

The books and papers this part follows are on screen and in the notes. Thank you for watching.

Where it goes next. The processes of chapter 10 return as Part 59's distributed algorithms. Part 60 describes hardware as programs whose meaning must match a specification, and Part 61 treats proof as a research method and puts the memory model for C on its map of open problems. Looking back, Part 54's verification and Part 55's trusted compilers rest on the soundness proofs given here.

Key results

The part's results in one place, for revision.

Kleene's fixed-point theorem\(\displaystyle \operatorname{fix}F=\bigsqcup_{k\ge 0}F^{k}(\bot)\quad\allowbreak \text{for }\allowbreak \text{continuous }F\text{ on }\allowbreak \text{a }\allowbreak \text{cpo}\)
Soundness and adequacy\(\displaystyle e\to^{*}v\ \Rightarrow\ [\![e]\!]=[\![v]\!],\qquad\allowbreak [\![e]\!]=n\ \Rightarrow\ e\to^{*}n\)
Bisimilarity is finer than traces\(\displaystyle a.(b+c)\ \not\sim\ a.b+a.c,\qquad\allowbreak \text{both }\allowbreak \text{have }\allowbreak \text{traces }\{\varepsilon,a,ab,ac\}\)
A free theorem\(\displaystyle r:\forall a.\,[a]\to[a]\ \ \Rightarrow\ \ \operatorname{map}f\circ r=r\circ\operatorname{map}f\)
Soundness of Hoare logic\(\displaystyle \vdash\{P\}\,c\,\{Q\}\ \ \Rightarrow\ \ \models\{P\}\,c\,\{Q\}\)
Monad laws, left unit\(\displaystyle \operatorname{return}a\ \mathbin{>\!\!>\!\!=}\ k\;=\;k\,a\)

Try it

Lab 58 · Three interpreters, one meaning

Generate 300 random terminating programs and run each by small steps, by the big-step evaluator and on the CEK machine; then compute the Kleene chain of the factorial functional, and test two free theorems, one of which must fail for a map that does not preserve order.

Figure produced by Lab 58: Three interpreters, one meaning
Produced by the lab below, seed 0, in 0.3 s.
python -m videos.cs.labs 58 needs numpy, scipy, matplotlib · download lab58.py · source on GitHub
programs on which the three semantics agree  300 of 300   (the theory says all)
mean steps per program                       small-step 72.9   CEK transitions 294.4
small steps of fact 0 ... fact 6             3  8  13  18  23  28  33   (5n + 3)
F^7(bottom) on 0 ... 7                       1  1  2  6  24  120  720  ⊥
map f . r = r . map f, four rearrangements   100% of 2,000 random lists each   (theory 100%)
sort commutes with f(x) = 2x + 1             100%   (f preserves order)
sort against g(x) = x * x                    fails on [-6, -15, 18, 3, -2, 14, 7]
a.(b + c) against a.b + a.c                  same traces: True   bisimilar: False   (6 blocks after 3 rounds)

Three definitions of running a program give one answer on every program tried, the Kleene iterates climb to factorial one input at a time, and a free theorem holds on every list until its hypothesis (an order-preserving map) is dropped.
The code (100 lines; it asserts its own result)
"""Lab 58: run one language three ways, climb Kleene's chain to factorial, and break a free theorem."""

from videos.coursekit import labs  # noqa: I001  (must stay first: it lets explainer.cs import without manim)

import math
import random

import numpy as np

from explainer.cs.semantics import meaning

TITLE = "Three interpreters, one meaning"
GOAL = ("Generate 300 random terminating programs and run each by small steps, by the big-step evaluator and on the "
        "CEK machine; then compute the Kleene chain of the factorial functional, and test two free theorems, one of "
        "which must fail for a map that does not preserve order.")
TASKS = [
    "Change big() so that it evaluates the right operand of an operation first. Does agreement() notice, and why not "
    "until the language has an effect such as an exception?",
    "Write the functional whose least fixed point is Fibonacci and iterate it from the empty function. On which "
    "inputs is the k-th iterate defined?",
    "In free_theorems(), replace g(x) = x * x by g(x) = -x. Sorting no longer commutes with map g: which property of "
    "g does Wadler's theorem need?",
]


def run(seed=0):
    lab = labs.Lab()

    # 1. three operational semantics on the same random programs
    rng = random.Random(seed)
    n, small_steps, cek_steps, agree = 300, [], [], 0
    for _ in range(n):
        p = meaning.random_program(rng)
        v1, ns, _ = meaning.small(p)
        v2 = meaning.big(p)
        v3, nc = meaning.cek(p)
        agree += meaning._val(v1) == meaning._val(v2) == meaning._val(v3)
        small_steps.append(ns)
        cek_steps.append(nc)
    small_steps, cek_steps = np.array(small_steps), np.array(cek_steps)
    lab.row("programs on which the three semantics agree", f"{agree} of {n}   (the theory says all)")
    lab.row("mean steps per program", f"small-step {small_steps.mean():.1f}   CEK transitions {cek_steps.mean():.1f}")
    assert agree == n, "small-step, big-step and the CEK machine must give the same value"
    assert cek_steps.mean() > 2 * small_steps.mean(), "the machine takes more, but cheaper, transitions"

    # 2. fact n by small steps: deterministic, so the run is one line; its length is 5 n + 3
    runs = [meaning.fact_trace(k) for k in range(7)]
    lab.row("small steps of fact 0 ... fact 6", "  ".join(str(r["steps"]) for r in runs) + "   (5n + 3)")
    assert all(r["value"] == math.factorial(r["n"]) and r["steps"] == 5 * r["n"] + 3 for r in runs)

    # 3. the Kleene chain: F^k(bottom) is factorial on 0 .. k-1 and undefined elsewhere
    chain = meaning.kleene(k_max=7, domain=8)
    for row in chain:
        expect = [math.factorial(m) if m < row["k"] else None for m in range(8)]
        assert row["table"] == expect, f"F^{row['k']}(bottom) is factorial exactly on 0 .. k - 1"
    lab.row("F^7(bottom) on 0 ... 7", "  ".join("⊥" if v is None else str(v) for v in chain[7]["table"]))

    # 4. free theorems, and the one that needs a hypothesis
    ft = meaning.free_theorems(trials=2000, seed=seed)
    worst = min(ft["rearrangements"].values())
    c = ft["sort_counterexample"]
    lab.row("map f . r = r . map f, four rearrangements", f"{worst:.0%} of 2,000 random lists each   (theory 100%)")
    lab.row("sort commutes with f(x) = 2x + 1", f"{ft['sort_monotone']:.0%}   (f preserves order)")
    lab.row("sort against g(x) = x * x", f"fails on {c['xs']}" if c else "no counterexample found")
    assert worst == 1.0 and ft["sort_monotone"] == 1.0, "a free theorem holds on every input"
    assert c is not None and c["sort_then_map"] != c["map_then_sort"], "squaring does not preserve order"
    assert sorted(c["sort_then_map"]) == c["map_then_sort"], "the two sides hold the same numbers, in different order"

    # 5. the same traces, not bisimilar
    b = meaning.bisim_examples()
    ch, ve = b["choice"], b["vending"]
    lab.row("a.(b + c) against a.b + a.c", f"same traces: {ch['same_traces']}   bisimilar: {ch['bisimilar']}   "
                                           f"({ch['blocks']} blocks after {ch['rounds']} rounds)")
    assert ch["same_traces"] and not ch["bisimilar"] and ve["bisimilar"]
    lab.note = ("Three definitions of running a program give one answer on every program tried, the Kleene iterates "
                "climb to factorial one input at a time, and a free theorem holds on every list until its hypothesis "
                "(an order-preserving map) is dropped.")

    fig, ax = labs.figure(2, size=(11, 4.4))
    ax[0].scatter(small_steps, cek_steps, s=12, color=labs.BLUE, alpha=0.7, label="one random program")
    hi = max(small_steps.max(), 2)
    grid = np.array([1, hi])
    ax[0].plot(grid, grid, color=labs.MUTED, ls="--", label="one transition per small step")
    ax[0].plot(grid, cek_steps.mean() / small_steps.mean() * grid, color=labs.GOLD,
               label=f"ratio of the means: {cek_steps.mean() / small_steps.mean():.1f}")
    ax[0].set(xscale="log", yscale="log", xlabel="small steps to a value", ylabel="CEK transitions",
              title=f"The same {n} programs on two machines")
    ax[0].legend(loc="upper left")
    table = np.array([[np.nan if v is None else np.log10(v) for v in row["table"]] for row in chain])
    ax[1].set_facecolor(labs.PANEL)
    ax[1].imshow(np.ma.masked_invalid(table), cmap="cividis", aspect="auto", vmin=-3.0, vmax=4.5)
    for k, row in enumerate(chain):
        for m, v in enumerate(row["table"]):
            ax[1].text(m, k, "⊥" if v is None else str(v), ha="center", va="center", fontsize=9,
                       color=labs.MUTED if v is None else labs.INK)
    ax[1].set(xlabel="input n", ylabel="iterate k", title="Kleene's chain: F^k(⊥) is factorial on 0 … k − 1",
              xticks=range(8), yticks=range(8))
    ax[1].grid(False)
    lab.fig = fig
    return lab

Now change it

  1. Change big() so that it evaluates the right operand of an operation first. Does agreement() notice, and why not until the language has an effect such as an exception?
  2. Write the functional whose least fixed point is Fibonacci and iterate it from the empty function. On which inputs is the k-th iterate defined?
  3. In free_theorems(), replace g(x) = x * x by g(x) = -x. Sorting no longer commutes with map g: which property of g does Wadler's theorem need?

Problems, with solutions

Try each problem before opening its solution.

  1. Determinism. Prove that small-step evaluation is deterministic for our language.

    Solution

    The rules are the search rules Op-L, Op-R, App-L, App-R and the one that steps the condition of an if, and the reduction rules Op, If-T, If-F, Beta and Fix. First, values never step: every rule's left-hand side is an operation, an application or a conditional, and n, b, fun x → e and fix f x → e are none of these. We prove, by induction on the derivation of e → e₁, that e → e₂ implies e₁ = e₂. Take e = e′ ⊕ e″. If e′ is not a value, only Op-L can apply (Op-R and Op need e′ to be a value), so both derivations end in Op-L, with premises e′ → e′₁ and e′ → e′₂, and the induction hypothesis gives e′₁ = e′₂. If e′ is a value and e″ is not, Op-L is excluded because values do not step and Op needs e″ to be a value, so only Op-R applies, and induction again. If both are values, neither search rule applies, and Op gives the one number n₁ ⊕ n₂ (or nothing, if they are not numbers: the term is stuck). An application is the same, with App-L, App-R and then Beta or Fix, chosen by the shape of the function value; substitution is a function, so the result is unique. A conditional steps its condition when that is not a value, and otherwise If-T or If-F, by whether it is true or false. So at most one rule fits any term, and its premise is unique by induction. Hence a run is a line, not a tree, and the value v with e →* v, if there is one, is unique: step in meaning.py can be a function for exactly this reason, and the 18-step trace of fact 3 is the only run there is.

  2. Kleene's chain. Show that the factorial functional is continuous, and that its least fixed point is factorial.

    Solution

    F takes a partial function h : ℤ ⇀ ℤ to F(h)(0) = 1, F(h)(n) = n · h(n − 1) for n ≠ 0 when h(n − 1) is defined, and undefined otherwise. Partial functions ordered by extension (h ⊑ h′ if h′ is defined wherever h is, and agrees) form a cpo: the least element ⊥ is the empty function, and a chain h₀ ⊑ h₁ ⊑ ⋯ has as least upper bound the union of the graphs, a function because members of a chain agree wherever both are defined. F is monotone: if h ⊑ h′ and F(h)(n) is defined, then either n = 0, and both give 1, or h(n − 1) is defined, so h′(n − 1) = h(n − 1) and F(h′)(n) = F(h)(n). F is continuous: ⊔ₖ F(hₖ) ⊑ F(⊔ₖ hₖ) by monotonicity; conversely, if F(⊔ₖ hₖ)(n) is defined, it consulted ⊔ₖ hₖ at the single point n − 1 (or not at all), which is already defined in some hₖ, so F(hₖ)(n) is defined with the same value. (F reads a finite part of its input, which is what continuity asks.) By Kleene's theorem the least fixed point is ⊔ₖ F^k(⊥). By induction on k, F^k(⊥) is defined exactly on {0, …, k − 1}, with value n! there: true for k = 0; F(F^k(⊥))(0) = 1; for n ≥ 1 it is defined iff n − 1 ∈ {0, …, k − 1}, that is n ∈ {1, …, k}, with value n · (n − 1)! = n!; and for n < 0, n − 1 is negative and never defined. (Our instrument's chain shows k = 0 to 7, ending 1, 1, 2, 6, 24, 120, 720.) The union is n ↦ n! on ℕ, undefined on the negative numbers, where the program indeed recurses forever. Least matters: the function that is 0 on the negative numbers is also a fixed point, and Kleene's theorem places every fixed point above each F^k(⊥), so above their union.

  3. Same traces, not bisimilar. Show that a.(b + c) and a.b + a.c have the same traces but are not bisimilar, with a distinguishing formula.

    Solution

    As transition systems: P →a P₁, P₁ →b P₂, P₁ →c P₃; and Q →a Q₁ →b Q₃, Q →a Q₂ →c Q₄. Both have the traces {ε, a, ab, ac}: Q reaches ab through Q₁ and ac through Q₂. Suppose R is a bisimulation with P R Q. The move P →a P₁ must be matched by Q →a Q₁ or Q →a Q₂ with P₁ R Qᵢ. If Q₁, then P₁ →c P₃ must be matched, and Q₁ has no c; if Q₂, then P₁ →b P₂ must be matched, and Q₂ has no b. Either way R fails, so P ≁ Q. The formula φ = ⟨a⟩(⟨b⟩true ∧ ⟨c⟩true) says "can do a and then both b and c": P ⊨ φ through P₁, and Q ⊭ φ, since Q₁ ⊭ ⟨c⟩true and Q₂ ⊭ ⟨b⟩true. (By the Hennessy–Milner theorem, image-finite states are bisimilar exactly when they satisfy the same formulas, so a non-bisimilar finite pair always has such a formula.) Our partition refinement shows the same thing: the first round splits states by the actions they can do, {P, Q}, {P₁}, {Q₁}, {Q₂} and the four end states; the second separates P from Q, because P's a leads into P₁'s block and Q's into Q₁'s and Q₂'s; the third changes nothing: 6 blocks after 3 rounds, with P and Q apart. Read a as a coin and b and c as tea and coffee: Q chooses your drink when it takes the coin.

  4. A free theorem. Derive the free theorem for r : ∀a. [a] → [a].

    Solution

    Read types as relations: at Int, equality; f ⟦A → B⟧ g iff x ⟦A⟧ y implies f x ⟦B⟧ g y; xs ⟦[A]⟧ ys iff the lists have the same length and are related element by element; t ⟦∀α. A⟧ t′ iff for all types X, X′ and every relation R between them, the instances t_X and t′_X′ are related at A with α read as R. Reynolds's abstraction theorem says that every closed term is related to itself at its type. For r this gives: for all A, B and R ⊆ A × B, if xs [R] ys then r_A xs [R] r_B ys. Now choose R to be the graph of a function f : A → B, a R b iff f a = b; then xs [R] ys says exactly map f xs = ys. Take ys = map f xs: the conclusion is map f (r_A xs) = r_B (map f xs), for every f, that is map f ∘ r = r ∘ map f. For example reverse [1, 2, 3] squared is [9, 4, 1], and [1, 4, 9] reversed is [9, 4, 1]. A corollary shows how little r can do: for xs of length n, let f i be the i-th element of xs, so that map f [0, …, n − 1] = xs; then r xs = map f (r [0, …, n − 1]): r can only select, drop, repeat and reorder positions, in a way that depends on the length alone. The proof assumes a total, pure language: with general recursion every type contains ⊥ and the theorem needs f strict (Wadler 1989); seq and run-time type tests weaken or break it. Our property test found no exception: reverse, take 3, every other and rotate each held on 100% of 2,000 random lists, with random f(x) = ax² + b, neither monotone nor one-to-one.

  5. Build. Add exceptions to our interpreters, and check the three still agree on random programs.

    Solution

    Solution notes. Add two terms to meaning.py: ("raise", e), which raises the integer value of e, and ("try", e, x, h), which runs e and, if it raises v, runs h with x bound to v; extend show and subst (the handler binds x, so substitution stops there, as at lam). Small step: a raised value is a final answer but not a value, so add is_final, and let small stop on either. Add propagation rules, one frame per step: when the subterm a search rule would step is ("raise", v) with v a value, the whole frame becomes ("raise", v), in both positions of an operation and of an application, in the condition of an if, and inside another raise; then try v ... → v, and try (raise v) with x -> h → h[v/x], with a search rule stepping the body. Big step: return tagged results, ("ok", v) or ("exn", n), and propagate the first exn premise in each rule, left to right; this is chapter 8's exceptions monad, with bind in every rule. (A Python exception class carrying n is the shorter alternative.) CEK: push a frame ("try", x, h, E) when entering a try and pop it when a value returns through it; on a raised value, pop frames until a try frame and continue with h in its environment extended by x, or return ("exn", n) if the stack empties. Extend _val so that an uncaught exception compares as ("exn", n). In random_program, generate raise with a small probability, often under a conditional (if e < k then raise n else e) so that only some runs raise, and wrap some subterms in try; termination is unaffected, since raising only ends a computation early. Then run agreement() on 300 programs and add a test beside test_three_semantics_agree that also requires raising and non-raising programs both to occur. Agreement now tests the order of evaluation as well as the values: in (raise 1) + (raise 2) all three must raise 1, so a big-step rule that evaluated the right operand first would be caught. The determinism proof of Problem 1 extends, because the propagation rules also fire only when everything to their left is a value.

  6. ★ Research. A relaxed-memory semantics for C without out-of-thin-air values.

    Discussion. Open. The C and C++ memory model, formalized by Batty et al. (2011), allows relaxed atomic loads to return values that justify themselves in a cycle: with x = y = 0 initially, thread 1 runs r1 = x; y = r1 and thread 2 runs r2 = y; x = r2, and the formal model does not forbid r1 = r2 = 42, although no known hardware or compiler produces it. The standard only recommends that implementations avoid such values. The obvious fixes each lose something. Forbidding cycles in program order together with reads-from (the choice of RC11, Lahav et al. 2017) rules out the 42, but also the outcome r1 = r2 = 1 of the same test without the dependency (each thread writes 1 instead of its register), which the ARM and Power architectures allow, so compiled relaxed loads must then be followed by a fence or a false dependency. Forbidding only cycles through dependencies fails because dependencies are not syntactic: compilers delete them (if (r1 == 1) y = 1; else y = 1; becomes y = 1), so a syntactic rule forbids valid optimizations. Operational models such as the promising semantics (Kang et al. 2017) and event-structure models take other routes, but no model has yet been accepted that forbids thin-air values, permits the optimizations compilers perform and compiles efficiently to the main processors, with all three proved. A good partial answer would fix a fragment (only relaxed and release/acquire accesses, say, or no read-modify-writes), give a model for it, and prove, preferably mechanically, that it forbids the standard thin-air litmus tests, validates a stated list of compiler transformations, and maps to x86, ARMv8 and Power without extra fences; or prove that no model in a natural class can have all three properties.

Notes and sources

Glossary

  • operational semantics: small-step (structural) and big-step (natural) — meaning as one step e → e′ at a time; meaning as a relation e ⇓ v from a term to its value.
  • value, call by value, search and reduction rules, derivation tree, determinism, stuck term — finished terms; arguments evaluated before the call; where to look and what to do; a step as a proof; at most one next step; a non-value with no step.
  • CEK machine: control, environment, continuation — an abstract machine whose stack of frames is explicit.
  • denotational semantics, denotation, semantic brackets ⟦·⟧, environment ρ, compositionality, context C[·] — meaning as a mathematical object, built only from the meanings of the parts; a program with a hole.
  • bottom (⊥), information order (⊑), flat domain ℤ⊥, pointwise order — no information; more defined; numbers side by side above ⊥; functions compared input by input.
  • complete partial order (cpo), chain, least upper bound, monotone, (Scott-)continuous — a least element and limits of chains; F of a limit is the limit of F.
  • functional, Kleene's fixed-point theorem, Kleene chain, least fixed point — fix F = ⊔ₙ Fⁿ(⊥) for continuous F.
  • D∞, domain equation D ≅ [D → D] — Scott's model of the untyped λ-calculus.
  • soundness, adequacy, full abstraction, PCF, parallel-or, sequentiality — the steps and the mathematics agree; the model distinguishes exactly what programs can; the function a sequential language cannot define.
  • logical relation, fundamental lemma, admissible relation, step-indexing — a relation built type by type; every program related to itself; closed under limits of chains; relations indexed by a number of steps.
  • game semantics, strategy, Opponent and Player — a type as a game, a program as a rule for its next move.
  • contextual equivalence (≅) — no context can tell two programs apart.
  • labelled transition system, trace equivalence, bisimulation, bisimilarity (∼), coinduction, greatest fixed point, Knaster–Tarski theorem — moves matched forever; the union of all bisimulations; exhibit one relation and check one step.
  • Hennessy–Milner logic, partition refinement — formulas ⟨a⟩φ that separate non-bisimilar states; splitting blocks until stable.
  • applicative bisimulation, Howe's method, congruence — bisimulation for functions, one argument at a time; the proof that it is preserved by every context.
  • reducibility (Tait), strong normalization, normalization by evaluation (NbE), read-back — Tait's predicate on types; every reduction stops; evaluate into a semantic domain, then read a normal form back.
  • parametricity, relational interpretation of types, abstraction theorem, representation independence, free theorem, shortcut (foldr/build) fusion — a polymorphic program respects every relation; a law read off a type.
  • derivable (⊢) and valid (⊨) triples, relative completeness, weakest liberal precondition (wlp), expressiveness, fixed-point induction — built from the rules against true of every run; complete given the true assertions; the states from which a command ends in Q or runs forever; assertions able to state wlp; a property closed under limits holds of a least fixed point.
  • monad, return, bind, monad laws, Kleisli composition, Kleisli category — computations T A; sequencing with the effect in the joints; effectful functions as arrows.
  • algebraic effect, operation, effect handler — an effect given by its operations; what each operation does, given the rest of the program as a continuation.
  • dependent function type (Π), dependent pair type (Σ), Vec A n, identity type, refl, definitional equality, structural recursion — types that depend on values; equality as a type; equal by computing; recursion on smaller arguments.
  • intensional and extensional type theory, calculus of constructions, proof assistant kernel — decidable against undecidable type checking; Coq's core; the small trusted checker of proof terms.
  • CCS: action, co-action, τ, prefix, choice, parallel composition, restriction; weak bisimulation — Milner's calculus of communicating systems; bisimulation with τ steps unseen.
  • CSP, π-calculus, scope extrusion, session types — Hoare's synchronous processes; names sent over names; a private name passed outside its scope; a channel's protocol as its type.
  • deadlock (reachable stuck state) — no move, and not finished.
  • mechanized semantics, univalence, homotopy type theory, cubical type theory — semantics checked by a proof assistant; equivalent types are equal; equalities as paths; a theory in which univalence computes.
  • relaxed memory model, out-of-thin-air value, load buffering — what concurrent loads may return; a value that justifies itself in a cycle; the litmus test where each thread reads before it writes.

Sources

  • G. Winskel, The Formal Semantics of Programming Languages: An Introduction (1993); R. Harper, Practical Foundations for Programming Languages (2nd ed., 2016); B. Pierce et al., Software Foundations (online); R. Milner, Communicating and Mobile Systems: the π-Calculus (1999).
  • G. Plotkin, "A structural approach to operational semantics", Aarhus University DAIMI FN-19, 1981; G. Kahn, "Natural semantics", STACS 1987; M. Felleisen and D. Friedman, "Control operators, the SECD-machine, and the λ-calculus", Formal Description of Programming Concepts III, 1986.
  • D. Scott and C. Strachey, "Toward a mathematical semantics for computer languages", Oxford PRG-6, 1971; D. Scott, "Outline of a mathematical theory of computation", Princeton Conference on Information Sciences and Systems, 1970; D. Scott, "Continuous lattices", Lecture Notes in Mathematics 274, 1972; A. Tarski, "A lattice-theoretical fixpoint theorem and its applications", Pacific J. Math. 1955.
  • G. Plotkin, "LCF considered as a programming language", Theoretical Computer Science 1977; S. Abramsky, R. Jagadeesan and P. Malacaria, "Full abstraction for PCF", and J. M. E. Hyland and C.-H. L. Ong, "On full abstraction for PCF: I, II and III", both Information and Computation 2000; H. Nickau, "Hereditarily sequential functionals", LFCS 1994.
  • D. Park, "Concurrency and automata on infinite sequences", GI Conference on Theoretical Computer Science 1981; M. Hennessy and R. Milner, "Algebraic laws for nondeterminism and concurrency", J. ACM 1985; P. Kanellakis and S. Smolka, "CCS expressions, finite state processes, and three problems of equivalence", PODC 1983; R. Paige and R. Tarjan, "Three partition refinement algorithms", SIAM J. Comput. 1987.
  • S. Abramsky, "The lazy lambda calculus", in Research Topics in Functional Programming (1990); D. Howe, "Proving congruence of bisimulation in functional programming languages", Information and Computation 1996; A. Appel and D. McAllester, "An indexed model of recursive types for foundational proof-carrying code", TOPLAS 2001.
  • W. Tait, "Intensional interpretations of functionals of finite type I", J. Symbolic Logic 1967; U. Berger and H. Schwichtenberg, "An inverse of the evaluation functional for typed λ-calculus", LICS 1991.
  • J. Reynolds, "Types, abstraction and parametric polymorphism", Information Processing 83 (IFIP 1983); P. Wadler, "Theorems for free!", FPCA 1989; A. Gill, J. Launchbury and S. Peyton Jones, "A short cut to deforestation", FPCA 1993.
  • C. A. R. Hoare, "An axiomatic basis for computer programming", Commun. ACM 1969; S. Cook, "Soundness and completeness of an axiom system for program verification", SIAM J. Comput. 1978.
  • E. Moggi, "Computational lambda-calculus and monads", LICS 1989, and "Notions of computation and monads", Information and Computation 1991; P. Wadler, "The essence of functional programming", POPL 1992; G. Plotkin and J. Power, "Adequacy for algebraic effects", FoSSaCS 2001; G. Plotkin and M. Pretnar, "Handlers of algebraic effects", ESOP 2009.
  • P. Martin-Löf, Intuitionistic Type Theory (1984); J.-Y. Girard, Interprétation fonctionnelle et élimination des coupures de l'arithmétique d'ordre supérieur (thesis, Université Paris VII, 1972); T. Coquand and G. Huet, "The calculus of constructions", Information and Computation 1988.
  • C. A. R. Hoare, "Communicating sequential processes", Commun. ACM 1978; R. Milner, A Calculus of Communicating Systems (LNCS 92, 1980); R. Milner, J. Parrow and D. Walker, "A calculus of mobile processes, I and II", Information and Computation 1992.
  • X. Leroy, "Formal verification of a realistic compiler", Commun. ACM 2009; R. Kumar, M. Myreen, M. Norrish and S. Owens, "CakeML: a verified implementation of ML", POPL 2014; A. Haas et al., "Bringing the web up to speed with WebAssembly", PLDI 2017; C. Watt, "Mechanising and verifying the WebAssembly specification", CPP 2018.
  • The Univalent Foundations Program, Homotopy Type Theory: Univalent Foundations of Mathematics (2013); C. Cohen, T. Coquand, S. Huber and A. Mörtberg, "Cubical type theory: a constructive interpretation of the univalence axiom", TYPES 2015.
  • M. Batty, S. Owens, S. Sarkar, P. Sewell and T. Weber, "Mathematizing C++ concurrency", POPL 2011; M. Batty, K. Memarian, K. Nienhuis, J. Pichon-Pharabod and P. Sewell, "The problem of programming language concurrency semantics", ESOP 2015; O. Lahav, V. Vafeiadis, J. Kang, C.-K. Hur and D. Dreyer, "Repairing sequential consistency in C/C++11", PLDI 2017; J. Kang, C.-K. Hur, O. Lahav, V. Vafeiadis and D. Dreyer, "A promising semantics for relaxed-memory concurrency", POPL 2017.
About this partfrom its README

Part 58 of a sixty-one-part course in computer science (see the series plan and the syllabus), the third part of Act XI, The Research Frontier. What does a program mean? Part 14 gave programs types; this part gives them meaning, three ways: as the steps a machine takes, as the mathematical object a program denotes, and as the laws it obeys. One small language with recursion is given three interpreters that must agree, a denotation in which recursion is a least fixed point, and proofs that the two meanings coincide; then the same ideas decide when two programs are the same, read theorems off types, prove Hoare logic sound, and stretch to effects, dependent types and communicating processes.

The instruments are in explainer/cs/semantics/ (tested in tests/test_cs58_semantics.py):

  • meaning.py: a PCF-like call-by-value language (integers, booleans, variables, functions, application, conditionals, + − × < =, and fix f x -> e) with three operational semantics that must agree: a small-step interpreter by substitution (left to right), a big-step evaluator with environments and closures, and a CEK machine with an explicit continuation stack; a generator of closed, terminating random programs and the agreement experiment (300 programs); the small-step trace of fact 3; the Kleene chain of the factorial functional on inputs 0 to 7; normalization by evaluation for the untyped λ-calculus in de Bruijn form (Python closures as the semantic domain, then read-back) against normal-order β-reduction on Church numerals; free theorems checked by property tests (2,000 random lists per rearrangement) with the counterexample for sort under a non-monotone map; strong bisimilarity by naive partition refinement, and trace sets to depth 3; one program run in the Maybe, State and List monads. (The scenes' illustrative pieces, such as the CEK run of (fun x -> x + 1) 2, the big-step tree, the factorial loop's states, the algebraic-effects handlers and the deadlock grid, whose states are enumerated by hand, are drawn inline.)
Chapter notes
  • Hook. Three meanings of factorial: as steps (our small-step interpreter rewrites fact 3 in 18 steps, down to 6), as a limit (the Kleene chain ⊥ ⊑ F(⊥) ⊑ F²(⊥) ⊑ ⋯) and as laws (equations and a Hoare triple). Why meaning matters: compiler correctness (CompCert, Part 54), refactoring (no context can tell old from new), language design (WebAssembly's formal specification). Our three interpreters agree on 300 of 300 random programs. The plan.
  • 1. Meaning as steps. The language and its values; factorial written with fix. Plotkin's structural operational semantics (1981): search rules (Op-L, Op-R, App-L, App-R) and reduction rules (Op, If-T, If-F, Beta, Fix), call by value, left to right. One step as a theorem: the derivation of 3 × fact (3 − 1) → 3 × fact 2 (Op-R, App-R, Op); determinism, by induction on derivations. The run of fact 3: the term grows as multiplications pile up (Part 11's call stack written into the term), then collapses to 6 after 18 steps. Kahn's natural semantics (1987): the derivation of (fun x → x × x)(1 + 2) ⇓ 9; e ⇓ v iff e →* v; our big-step evaluator agrees with the small-step interpreter on 300 of 300 random programs. The CEK machine (Felleisen and Friedman 1986): an illustrative run of (fun x -> x + 1) 2 in eleven configurations; a mean of 294.4 CEK transitions per random program against 72.9 small steps, each transition constant work while each small step searches and copies the whole term; the interpreter loop of Part 15, derived from the rules.
  • 2. Meaning as mathematics. Scott and Strachey (1971): fun x -> x * x and fun x -> x * x + 0 denote the same squaring function, a set of pairs. One equation per construct, with an environment ρ and ⊥ for a term that never finishes; compositionality, meanings flowing up the tree of (1 + 2) × x to 12 at x = 4. The meaning of (fun x → x × x)(1 + 2) computed by algebra alone: 9, the big-step tree's answer. Contexts: equal meanings stay equal in every context, which licenses Part 13's optimizer to rewrite x × x + 0 to x × x. Recursion as an equation g = F(g); for factorial two fixed points, one undefined on the negative numbers and one 0 there; fact (-1) never stops, so the meaning is the least defined solution.
  • 3. Domains and fixed points. Ordering by information: ℤ⊥ flat; partial functions pointwise (f ⊑ g, but f ⋢ h when h changes an answer). Complete partial orders: a least element, and least upper bounds of chains. Monotone and continuous functions; H (1 on total functions, ⊥ otherwise) is monotone but not continuous: ⊔ H(g_k) = ⊥ along the partial factorials, yet H(⊔ g_k) = 1, and H would decide totality, a cousin of Part 25's halting problem. Kleene's fixed-point theorem, proved in three steps (a chain; a fixed point, by continuity; the least, by induction), with Part 13's liveness analysis as the finite case. The Kleene chain of factorial computed: F^k(⊥) is defined on 0, …, k − 1, rows k = 0 to 7 reaching 1, 1, 2, 6, 24, 120, 720; the limit is factorial on ℕ, still undefined on negative numbers; a while loop's meaning the same way. Scott's D∞ (1969): D ≅ [D → D] is impossible for all set functions (Cantor), possible for continuous ones, as the limit of D₀, D₁ = [D₀ → D₀], ….
  • 4. Adequacy and full abstraction. Two meanings of fact 3, both 6. Soundness (e →* v ⇒ ⟦e⟧ = ⟦v⟧) and adequacy (⟦e⟧ = n ⇒ e →* n, for closed integer programs), proved by Plotkin for PCF (1977). Soundness of Beta by a substitution lemma, of Fix by the fixed-point equation. Adequacy fails by naive induction at an application, so a logical relation, a ladder of types (simplified after Winskel's proof for an eager language); the fundamental lemma, with fix handled through the Kleene chain (shown on inputs 0 to 4) and admissibility; at type int it is adequacy. Contextual equivalence; full abstraction fails for PCF: parallel-or is continuous but no sequential program computes it, so two tests that differ only on parallel-or are contextually equivalent with different meanings; adding parallel-or makes Scott's model fully abstract. Game semantics (Abramsky, Jagadeesan and Malacaria; Hyland and Ong; Nickau, in the 1990s): the strategy of not in four moves, sequentiality built in.
  • 5. When are two programs the same? fun x -> x + x against fun x -> 2 * x in three contexts (10, 7 and 4 for both), out of infinitely many. a.(b + c) against a.b + a.c: the same traces {ε, a, ab, ac}, but the attacker wins the bisimulation game, and the Hennessy–Milner formula ⟨a⟩(⟨b⟩true ∧ ⟨c⟩true) tells them apart. Park's bisimulation (1981) as the greatest fixed point of a monotone F (Knaster–Tarski), and coinduction. Two vending machines proved bisimilar by exhibiting R = {(V₁, W₁), (V₂, W₂), (V₁, W₃)} and checking one step; our partition refinement finds 2 blocks after 2 rounds (V₁ ∼ W₁) for them and 6 blocks after 3 rounds (P ≁ Q) for the pair above. Applicative bisimulation (Abramsky 1990), relating the two doubling functions; Howe's method makes it a congruence. Logical relations between programs: the fundamental property gives contextual equivalence with no context examined; with fix, admissibility or step-indexing (Appel and McAllester 2001). Tait's reducibility (1967), and normalization by evaluation (Berger and Schwichtenberg 1991): our NbE and normal-order reduction reach the same normal form on 2 + 3, 2 × 3, 3 × 4, 2³ and 3³ (5, 6, 12, 8, 27; normal order takes 6, 7, 9, 16 and 28 β-steps).
  • 6. Theorems for free. Reynolds's two counters (one counts up; the other counts down and reads its state negated) related by m = −n; the abstraction theorem (1983) and "type structure is a syntactic discipline for enforcing levels of abstraction". Every type read as a relation (Int, →, lists, ∀). The free theorem for r : ∀a. [a] → [a] derived: map f ∘ r = r ∘ map f. The square for reverse and squaring; reverse, take 3, every other and rotate each held on 100% of random lists with random f(x) = ax² + b (Part 14 tested linear f only). Wadler (1989): sort commutes with map f when f preserves and reflects the order; f(x) = 2x + 1 held on 100% of random lists; for g(x) = x² our test found [−6, −15, 18, 3, −2, 14, 7], where sorting then squaring gives [225, 36, 4, 9, 49, 196, 324] and squaring then sorting gives [4, 9, 36, 49, 196, 225, 324] (−15 < −6 but 225 > 36). Where the theorem bends (a Java identity with instanceof; general recursion, which needs f strict; Haskell's seq) and where it pays (foldr/build fusion in GHC, Gill, Launchbury and Peyton Jones 1993; representation independence).
  • 7. Hoare logic, proved sound. Derivable (⊢, a derivation such as the Seq tree for {x > 4} x := x + 1; y := x {y > 5}) against true (⊨, every run from P that ends, ends in Q); soundness, and Cook's relative completeness (1978). Big-step rules for commands, with the loop in its own premise. Soundness by induction on the derivation: assignment through a substitution lemma, then Seq and Consequence. The while case: factorial as a loop with invariant x ≥ 0 ∧ y · x! = 3!, run from x = 3 through (x, y) = (3, 1), (2, 3), (1, 6), (0, 6), leaving with y = 6; an inner induction on the run's derivation. The same proof against the denotation: the loop as fix Φ, safety closed under limits of chains, Scott's fixed-point induction (the loop's iterates from y = 1 end in the numbers of chapter three's chain). Cook's proof through the weakest liberal precondition; why only relative: {true} skip {P} holds iff P is true, and by Gödel (1931) no proof system lists every true statement of arithmetic. Part 54's tools discharge exactly those assertions.
  • 8. Effects and monads. Moggi (1989, 1991): a computation of an integer means an element of T ℤ; failure (ℤ + {err}), state (S → ℤ × S) and choice (List ℤ). Return and bind as plumbing; a do block is bind (Wadler 1992). One program in three monads: Maybe gives Nothing, Just 5 and Just 4 for b = 0, 3 and 4; State (tick twice from 0, return ten times the counter) gives (20, 2); List (b from 1 to 4) gives [12, 6, 4, 3]. The three monad laws, the left unit checked for State by algebra; Kleisli composition, a category with return as identity; Moggi's let as bind. Algebraic effects (Plotkin and Power 2001) and handlers (Plotkin and Pretnar 2009): if choose () then 6 else if choose () then 4 else fail () as a tree, run by a handler that collects every result ([6, 4]) and by one that backtracks (6); OCaml 5, Koka and Eff.
  • 9. Dependent types. Π and Σ as columns over A, becoming → and × when B does not depend on x; Martin-Löf's type theory (from 1972). Vec A n: nil, cons, head on Vec A (n + 1), append; [7, 2] appended to [5] has type Vec ℕ (2 + 1), which the checker computes to Vec ℕ 3; head nil is rejected before the program runs. Propositions as types extended (Part 14): ∀ as Π, ∃ as Σ, equality as a type made by refl; Π(n:ℕ). Σ(m:ℕ). n < m proved by the program λn. (n + 1, lt_succ n). 2 + 2 = 4 proved by refl, because 2 + 2 computes to 4 in four lines; n + 0 = n does not compute and is proved by a recursive function: induction is recursion. Why every program must terminate: type equality by normalization, and bad = bad would prove False; structural recursion; normalization by Tait's method, extended to polymorphism by Girard (1972); intensional equality keeps checking decidable, Martin-Löf's extensional theory (1984) does not. A proof assistant's kernel: the calculus of constructions (Coquand and Huet 1988) at the core of Coq; tactics and the elaborator untrusted, the kernel trusted.
  • 10. Processes and channels. CCS (Milner 1980): actions a, ā, τ; 0, α.P, P + Q, P | Q, (νa)P and named processes; a customer coin‾.tea.0 and a machine coin.tea‾.V, joined and restricted; Hoare's CSP (1978) and Go's channels. The rules Act, Sum, Par, Com and Res; the first τ step derived; the closed system takes two τ steps and stops, and is weakly bisimilar to 0; strong bisimilarity is preserved by every CCS operator. The π-calculus (Milner, Parrow and Walker 1992): names sent over names, and scope extrusion of a private channel. Deadlock: two threads taking two locks (Part 33) in opposite orders, as CCS processes; the state grid (enumerated by hand) has 19 reachable states, 22 τ steps and 2 states with no move, the finish and the deadlock; finding one is a search, as in Part 54's model checker; session types (Part 43).
  • 11. Frontier: semantics of real languages. Mechanized semantics at full size: CompCert's C (Leroy 2009), CakeML (Kumar et al. 2014), WebAssembly's small-step specification and its type soundness in Isabelle (Haas et al. 2017; Watt 2018); still missing, C's concurrency (Part 33's out-of-thin-air problem) and most languages people write. Equality rethought: proofs of equality as values, Voevodsky's univalence, equalities as paths; homotopy type theory (the HoTT book, 2013), and cubical type theory, in which univalence computes. Four open problems and the ★ research problem.
  • Outro. Recap, payoffs (Parts 59, 60 and 61; back to Parts 54 and 55), practice, problems, next part (Part 59, Distributed Computing Theory).

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Operational semantics: small-step and big-step for a language with recursion; determinism; the CEK machine (callback to Part 15).
  2. Denotational semantics: what a program denotes; compositionality; recursion as a least fixed point.
  3. Domain theory: complete partial orders, continuity, Kleene's fixed-point theorem (callback to Part 13's lattices); Scott's D∞ model of the untyped λ-calculus (1969).
  4. Adequacy and full abstraction; Plotkin's PCF and parallel-or (1977); game semantics' answer (1990s).
  5. Program equivalence: contextual equivalence; bisimulation; logical relations, and normalization of the simply typed λ-calculus proved with them (Tait).
  6. Parametricity: Reynolds (1983), Wadler's Theorems for free! (1989), derived for map and sort.
  7. Axiomatic semantics revisited (Part 54): Hoare logic proved sound against the operational semantics.
  8. Effects: monads (Moggi 1991), algebraic effects and handlers; state, exceptions, nondeterminism as monads.
  9. Dependent types: Martin-Löf type theory, propositions as types extended (Part 14); a proof assistant's kernel.
  10. Concurrency semantics: CCS and the π-calculus; session types (callback to Part 43).
  11. Frontier: mechanized semantics of real languages (CompCert's C, CakeML, WebAssembly); homotopy type theory; open problems.
  12. Outro.

Computed: a small-step interpreter, a big-step interpreter and a CEK machine for the same language, agreeing on random programs; Kleene iterates of a recursive definition converging; normalization by evaluation; free theorems checked by property tests; bisimulation checked by our model checker (Part 54). Visuals: the Kleene chain rising through a cpo; logical relations as a ladder of types; a bisimulation game played between two transition systems. In practice: language design and specification (WebAssembly's formal spec), compilers' correctness arguments, refactoring tools, effect systems in modern languages. Reading: Winskel, The Formal Semantics of Programming Languages; Harper, Practical Foundations for Programming Languages; Pierce et al., Software Foundations; Scott 1970; Plotkin 1977; Reynolds 1983; Wadler 1989; Moggi 1991; Milner, Communicating and Mobile Systems.

中文讲义

本讲的中文部分(与英文版对应)。

习题与解答
  1. 确定性。 证明我们的语言的小步求值是确定的。

    解答

    规则包括搜索规则 Op-L、Op-R、App-L、App-R 和对 if 的条件走一步的那条规则,以及归约规则 Op、If-T、If-F、 Beta 和 Fix。首先,值不会走步:每条规则的左边都是一个运算、一个应用或一个条件式,而 n、b、fun x → e 和 fix f x → e 都不是。我们对 e → e₁ 的推导作归纳,证明 e → e₂ 蕴含 e₁ = e₂。取 e = e′ ⊕ e″。若 e′ 不是值,只有 Op-L 适用(Op-R 和 Op 都要求 e′ 是值),所以两个推导都以 Op-L 结尾,前提分别是 e′ → e′₁ 和 e′ → e′₂,由归纳假设 e′₁ = e′₂。若 e′ 是值而 e″ 不是,Op-L 被排除(值不走步),Op 要求 e″ 是值,所以只有 Op-R 适用,再用归纳。若两者都是值,两条搜索规则都不适用, Op 给出唯一的数 n₁ ⊕ n₂(如果它们不是数,就什么也不给:这个项卡住了)。应用的情形相同:App-L、App-R,然后按函数值的 形状选 Beta 或 Fix;代换是一个函数,所以结果唯一。条件式在条件不是值时对条件走一步,否则按条件为真或假用 If-T 或 If-F。 所以任何项至多有一条规则适用,而它的前提由归纳也是唯一的。因此一次运行是一条线而不是一棵树,满足 e →* v 的值 v (若存在)是唯一的:meaning.py 里的 step 能写成一个函数正是因为这一点,fact 3 的 18 步轨迹也是唯一的运行。

  2. 克莱尼链。 证明阶乘泛函是连续的,并且它的最小不动点就是阶乘。

    解答

    F 把部分函数 h : ℤ ⇀ ℤ 映到 F(h)(0) = 1;当 n ≠ 0 且 h(n − 1) 有定义时 F(h)(n) = n · h(n − 1);否则无定义。 部分函数按延拓排序(h′ 在 h 有定义处都有定义且与之一致时 h ⊑ h′),构成一个完全偏序:最小元 ⊥ 是空函数,链 h₀ ⊑ h₁ ⊑ ⋯ 的最小上界是各图像之并,它是一个函数,因为链中的成员在都有定义处一致。F 是单调的:若 h ⊑ h′ 且 F(h)(n) 有定义,则要么 n = 0,两边都是 1;要么 h(n − 1) 有定义,于是 h′(n − 1) = h(n − 1),F(h′)(n) = F(h)(n)。F 是连续的: 由单调性 ⊔ₖ F(hₖ) ⊑ F(⊔ₖ hₖ);反过来,若 F(⊔ₖ hₖ)(n) 有定义,它只在一个点 n − 1 上查看了 ⊔ₖ hₖ(或者根本没看),这个点 已经在某个 hₖ 中有定义,所以 F(hₖ)(n) 有定义且值相同。(F 只读取输入的有限部分,这正是连续性的要求。)由克莱尼定理, 最小不动点是 ⊔ₖ F^k(⊥)。对 k 归纳:F^k(⊥) 恰好在 {0, …, k − 1} 上有定义,值为 n!。k = 0 时成立;F(F^k(⊥))(0) = 1; n ≥ 1 时它有定义当且仅当 n − 1 ∈ {0, …, k − 1},即 n ∈ {1, …, k},值为 n · (n − 1)! = n!;n < 0 时 n − 1 为负,永远 无定义。(我们的仪器算出的链从 k = 0 到 7,最后是 1、1、2、6、24、120、720。)它们的并是 ℕ 上的 n ↦ n!,在负数上无 定义,而程序在那里确实永远递归下去。“最小”很要紧:在负数上取 0 的函数也是不动点,而克莱尼定理把每个不动点都放在每个 F^k(⊥) 之上,因而在它们的并之上。

  3. 迹相同,却不互模拟。 证明 a.(b + c) 与 a.b + a.c 有相同的迹,却不互模拟,并给出一个区分它们的公式。

    解答

    写成迁移系统:P →a P₁,P₁ →b P₂,P₁ →c P₃;Q →a Q₁ →b Q₃,Q →a Q₂ →c Q₄。两者的迹都是 {ε, a, ab, ac}: Q 经 Q₁ 得到 ab,经 Q₂ 得到 ac。假设 R 是一个互模拟且 P R Q。动作 P →a P₁ 必须由 Q →a Q₁ 或 Q →a Q₂ 匹配,并且 P₁ R Qᵢ。若是 Q₁,则 P₁ →c P₃ 必须被匹配,而 Q₁ 没有 c;若是 Q₂,则 P₁ →b P₂ 必须被匹配,而 Q₂ 没有 b。两种情况 R 都不成立,所以 P ≁ Q。公式 φ = ⟨a⟩(⟨b⟩true ∧ ⟨c⟩true) 说的是“能做 a,然后 b 和 c 都能做”:P 经 P₁ 满足 φ,Q 不满足 φ,因为 Q₁ ⊭ ⟨c⟩true,Q₂ ⊭ ⟨b⟩true。(由亨尼西–米尔纳定理,像有限的状态互模拟当且仅当它们满足相同的公式,所以不互模拟 的有限对总有这样的公式。)我们的划分细化给出同样的结论:第一轮按能做的动作把状态分开,得到 {P, Q}、{P₁}、{Q₁}、{Q₂} 和四个终止状态;第二轮把 P 和 Q 分开,因为 P 的 a 通向 P₁ 所在的块,而 Q 的 a 通向 Q₁ 和 Q₂ 的块;第三轮没有变化: 3 轮之后 6 个块,P 与 Q 分处两块。把 a 读作投币,b、c 读作茶和咖啡:Q 在收下硬币时就替你选好了饮料。

  4. 一条免费定理。 推导 r : ∀a. [a] → [a] 的免费定理。

    解答

    把类型读作关系:Int 上是相等;f ⟦A → B⟧ g 当且仅当 x ⟦A⟧ y 蕴含 f x ⟦B⟧ g y;xs ⟦[A]⟧ ys 当且仅当两个列表 长度相同且逐个元素相关;t ⟦∀α. A⟧ t′ 当且仅当对任意类型 X、X′ 和它们之间的任意关系 R,实例 t_X 与 t′_X′ 在把 α 读作 R 的 A 上相关。雷诺兹的抽象定理说:每个闭项在它自己的类型上与自身相关。对 r 而言:对任意 A、B 和 R ⊆ A × B,若 xs [R] ys,则 r_A xs [R] r_B ys。现在取 R 为函数 f : A → B 的图像,a R b 当且仅当 f a = b;于是 xs [R] ys 恰好是 map f xs = ys。取 ys = map f xs,结论就是 map f (r_A xs) = r_B (map f xs),对每个 f 都成立,即 map f ∘ r = r ∘ map f。例如 reverse [1, 2, 3] 再平方是 [9, 4, 1],[1, 4, 9] 再反转也是 [9, 4, 1]。一个推论说明 r 能做 的事有多少:对长度为 n 的 xs,令 f i 为 xs 的第 i 个元素,则 map f [0, …, n − 1] = xs,于是 r xs = map f (r [0, …, n − 1]):r 只能挑选、丢弃、重复和重排位置,而且方式只取决于长度。这个证明假定语言是全的、纯的: 有一般递归时每个类型都含 ⊥,定理需要 f 是严格的(Wadler 1989);seq 和运行时类型测试会削弱乃至破坏它。我们的性质 测试没有发现例外:reverse、take 3、隔一取一和轮转在各 2,000 个随机列表上都 100% 成立,f(x) = ax² + b 随机选取, 既不单调也不是一一的。

  5. 动手。 给我们的解释器加上异常,并检查三者在随机程序上仍然一致。

    解答

    解答要点。 在 meaning.py 里加两种项:("raise", e) 抛出 e 的整数值;("try", e, x, h) 运行 e,若它抛出 v,就在 x 绑定为 v 的情况下运行 h。扩展 show 和 subst(处理器绑定 x,所以代换在那里停下,和 lam 一样)。小步:被抛出的 值是最终答案但不是值,所以加一个 is_final,让 small 在两者之一时停下。加上传播规则,每步一层:当搜索规则要走一步的 子项是 ("raise", v) 且 v 是值时,整个外层变成 ("raise", v);这适用于运算和应用的两个位置、if 的条件,以及另一个 raise 的内部;然后 try v ... → v,try (raise v) with x -> h → h[v/x],并有一条搜索规则对主体走一步。大步:返回带标签 的结果 ("ok", v) 或 ("exn", n),每条规则从左到右把第一个 exn 前提传播出去;这就是第 8 章的异常单子,每条规则里都 有一次 bind。(用一个携带 n 的 Python 异常类是更短的写法。)CEK:进入 try 时压入帧 ("try", x, h, E),值经过它返回时 弹出;遇到被抛出的值时,一直弹帧直到 try 帧,在它的环境加上 x 后继续运行 h;若栈空了,就返回 ("exn", n)。扩展 _val,使未捕获的异常比较为 ("exn", n)。在 random_program 中以小概率生成 raise,常常放在条件式下 (if e < k then raise n else e),使只有一部分运行会抛出,并把一些子项包进 try;终止性不受影响,因为抛出只会让计算 提前结束。然后在 300 个程序上运行 agreement(),并在 test_three_semantics_agree 旁加一个测试,同时要求抛出和不抛出的 程序都出现。现在一致性检验的不仅是值,还有求值顺序:在 (raise 1) + (raise 2) 中三者都必须抛出 1,所以一条先求右操作数 的大步规则会被抓住。第 1 题的确定性证明可以推广,因为传播规则也只在它左边的一切都是值时才触发。

  6. ★ 研究。 一个没有凭空出现的值的 C 宽松内存语义。

    讨论。 尚未解决。Batty 等人(2011)形式化的 C 和 C++ 内存模型允许宽松的原子读返回在一个环中自我证明的值:初始 x = y = 0,线程 1 执行 r1 = x; y = r1,线程 2 执行 r2 = y; x = r2,形式模型并不禁止 r1 = r2 = 42,尽管已知的硬件和 编译器都不会产生它。标准只建议实现避免这样的值。显而易见的修补各有损失。禁止程序顺序与读取来源(reads-from)合起来成环 (RC11 的选择,Lahav 等人 2017)排除了 42,却也排除了同一测试去掉依赖后(每个线程写 1 而不是写寄存器)的结果 r1 = r2 = 1,而 ARM 和 Power 架构允许这个结果,于是编译出来的宽松读后面必须跟一个栅栏或一个假依赖。只禁止经过 依赖的环也不行,因为依赖不是语法上的东西:编译器会删掉它们(if (r1 == 1) y = 1; else y = 1; 变成 y = 1),所以一条 语法规则会禁止合法的优化。承诺语义(promising semantics,Kang 等人 2017)这类操作模型和基于事件结构的模型走了别的路, 但还没有一个模型被接受,能同时禁止凭空之值、允许编译器实际做的优化、高效地编译到主流处理器,并且三者都有证明。好的部分 答案可以固定一个片段(比如只有宽松访问和释放/获取访问,或者没有读-改-写),为它给出一个模型,并证明(最好是机器检查的 证明)它禁止标准的凭空值试金石测试、验证一张列明的编译器变换清单、无需额外栅栏就能映射到 x86、ARMv8 和 Power;或者证明 某个自然的模型类中没有模型能同时具备这三条性质。

Build the film

python -m videos.cs.cs58.compute        # the part's numbers, into .cache/cs58
python tools/build.py cs58                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs58 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/cs/cs58. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build it
python -m videos.cs.cs58.compute
python -m unittest tests.test_cs58_semantics
python tools/build.py cs58