my blog lives here now
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

380 lines
22 KiB

6 years ago
2 years ago
6 years ago
2 years ago
6 years ago
  1. ---
  2. title: The Semantics of Evaluation & Continuations
  3. date: July 12th, 2020
  4. maths: true
  5. ---
  6. Continuations are a criminally underappreciated language feature. Very few languages (off the top of my head: most Scheme dialects, some Standard ML implementations, and Ruby) support the---already very expressive---undelimited continuations---the kind introduced by `call/cc`{.scheme}---and even fewer implement the more expressive delimited continuations. Continuations (and tail recursion) can, in a first-class, functional way, express _all_ local and non-local control features, and are an integral part of efficient implementations of algebraic effects systems, both as language features and (most importantly) as libraries.
  7. <div class="text-image">
  8. <div>
  9. Continuations, however, are notoriously hard to understand. In an informal way, we can say that a continuation is a first-class representation of the "future" of a computation. By this I do not mean a future in the sense of an asynchronous computation, but in a temporal sense. While descriptions like this are "correct" in some sense, they're also not useful. What does it mean to store the "future" of a computation in a value?
  10. Operationally, we can model continuations as just a segment of control stack. This model is perhaps better suited for comprehension by programmers familiar with the implementation details of imperative programming languages, which is decidedly not my target audience. Regardless, this is how continuations (especially the delimited kind) are generally presented.
  11. With no offense to the authors of these articles, some of which I greatly respect as programming language designers and implementers, I do not think that this approach is very productive in a functional programming context. This reductionist, imperative view would almost be like explaining the _concept_ of a proper tail call by using a trampoline, rather than presenting trampolines as one particular implementation strategy for the tail-call-ly challenged.
  12. </div>
  13. <figure>
  14. <img class="tikzpicture" src="/diagrams/cc/delimcc.svg" />
  15. _Fig 1. A facsimile of a diagram you'd find attached to an explanation of delimited continuations. Newer frames on top._
  16. </figure>
  17. </div>
  18. In a more functional context, then, I'd like to present the concept of continuation as a _reification_ of an _evaluation context_. I stress that this presentation is not novel, though it is, perhaps, uncommon outside of the academic literature on continuations. Reification, here, is the normal English word. It's a posh way of saying "to make into a thing". For example, an `(eval)`{.scheme} procedure is a _reification_ of the language implementation---it's an interpreter made into a thing, a thing that looks, walks and quacks like a procedure.
  19. The idea of evaluation contexts, however, seems to have remained stuck in the ivory towers that the mainstream so often accuse us of inhabiting.
  20. Evaluation Contexts
  21. -------------------
  22. What _is_ an evaluation context? Unhelpfully, the answer depends on the language we're talking about. Since the language family you're most likely to encounter continuations in is Scheme, we'll use a Scheme-_like_ language (not corresponding to any of the R<sup>K</sup>RS standards). Our language has the standard set of things you'd find in a minimalist functional language used for an academic text: lambda expressions, written `(lambda arg exp)`{.scheme} that close over variables in lexical scope; applications, also n-ary, written `(func arg )`{.scheme}, `if`{.scheme}-expressions written `(if condition then else)`{.scheme}, with the `else` expression being optional and defaulting to the false value `#f`{.scheme}, integers, integer operations, and, of course, variables.
  23. As an abbreviation one can write `(lambda (a . args) body)` to mean `(lambda a (lambda args body))` (recursively), and similarily for applications (associating to the left), but the language itself only has unary application and currying. This is in deviation from actual Scheme implementations which have complex parameter passing schemes, including variadic arguments (collecting any overflow in a list), keyword and optional arguments, etc. While all of these features are important for day-to-day programming, they do nothing but cloud the presentation here with needless verbosity.
  24. ```scheme
  25. e ::= (lambda arg expr) ; function definitions
  26. | (if expr expr expr) ; if expression
  27. | (expr expr) ; function applications
  28. | var ; variables
  29. | #t | #f ; scheme programmers spell booleans funny
  30. | 1 | 2 | 3 | 4 ... ; integers
  31. ```
  32. The set of values in this miniScheme language inclues lambda expressions, the booleans `#t`{.scheme} and `#f`{.scheme}, and the integers; Every other expression can potentially take a step. Here, taking a step means applying a _reduction rule_ in the language's semantics, or finding a _congruence_ rule that allows some sub-expression to suffer a reduction rule.
  33. An example of reduction rule is &beta;-reduction, which happens when the function being applied is a &lambda;-abstraction and all of its arguments have been reduced to values. The rule, which says that an application of a lambda to a value can be reduced to its body in one step, is generally written in the notation of sequent calculus as below.
  34. <details>
  35. <summary>Fancy reduction rule type-set in TeX</summary>
  36. <noscript>Sorry, I use KaTeX for my mathematics. Read on!</noscript>
  37. $$\frac{}{(\lambda x.e) v \longrightarrow e\{v/x\}}$$
  38. </details>
  39. However, let's use the Lisp notation above and write reduction rules as if they were code. The notation I'm using here is meant to evoke [Redex], a tool for defining programming semantics implemented as a Racket language. Redex is really neat and I highly recommend it for anyone interested in studying programming language semantics formally.
  40. [Redex]: https://docs.racket-lang.org/redex/
  41. <!-- reduction rules -->
  42. <div style="display: flex; flex-direction: column; justify-content: space-around">
  43. <h4 style="text-align: center">Reduction rules</h4>
  44. <div class="mathpar">
  45. <div>
  46. ```scheme
  47. (--> ((lambda x e) v)
  48. (subst x v e))
  49. ```
  50. </div>
  51. <div>
  52. ```scheme
  53. (--> (if #t e_1 e_2)
  54. (e_1))
  55. ```
  56. </div>
  57. <div>
  58. ```scheme
  59. (--> (if #f e_1 e_2)
  60. (e_2))
  61. ```
  62. </div>
  63. </div>
  64. </div>
  65. These rules, standard though they may be, have a serious problem. Which, you might ask? They only apply when the expressions of interest are already fully evaluated. No rule matches for when the condition of an `if`{.scheme} expression is a function application, or another conditional; The application rule, also, only applies when the argument has already been evaluated (it's _call-by-value_, or _strict_). What can we do? Well, a simple and obvious solution is to specify _congruence_ rules that let us reduce in places of interest.
  66. <!-- congruence rules -->
  67. <div style="display: flex; flex-direction: column; justify-content: space-around">
  68. <h4 style="text-align: center">Congruence rules</h4>
  69. <div class="mathpar">
  70. <div>
  71. ```scheme
  72. [ (--> e_1 v)
  73. --------------------------
  74. (--> (e_1 e_2) (v e_2))]
  75. ```
  76. Evaluating in function position
  77. </div>
  78. <div>
  79. ```scheme
  80. [ (--> e_2 v)
  81. --------------------------
  82. (--> (e_1 e_2) (e_1 v))]
  83. ```
  84. Evaluating in argument position
  85. </div>
  86. <div>
  87. ```scheme
  88. [ (--> e_1 v)
  89. -----------------------
  90. (--> (if e_1 e_2 e_3)
  91. (if v e_2 e_3))]
  92. ```
  93. Evaluating in scrutinee position
  94. </div>
  95. </div>
  96. </div>
  97. Hopefully the problem should be clear. If it isn't, consider adding binary operators for the field operations: Each of the 4 (addition, subtraction, multiplication, division) needs 2 congruence rules, one for reducing either argument, even though they each have a single reduction rule. In general, an N-ary operator will have N congruence rules, one for each of its N operands, but only one reduction rule!
  98. The solution to this problem comes in the form of _evaluation contexts_. We can define a grammar of "expressions with holes", generally written as <noscript>E[·]</noscript><span class='script'>$\operatorname{E}[\cdot]$</span>, where the <noscript>·</noscript><span class='script'>$\cdot$</span> stands for an arbitrary expression. In code, we'll denote the hole with `<>`, perhaps in evocation of the macros `cut` and `cute` from SRFI 26[^1].
  99. Our grammar of evaluation contexts, which we'll call `E` in accordance with tradition, looks like this:
  100. ```scheme
  101. E ::= <> ; any expression can be evaluated
  102. | (E e) ; evaluate the function
  103. | (v E) ; evaluate the argument
  104. | (if E e e) ; evaluate the condition
  105. ```
  106. Now we can write all our congruence rules by appealing to a much simpler, and most importantly, singular, _context rule_, that says reduction is legal anywhere in an evaluation context.
  107. <div style="text-align: center;">
  108. <div style="display: inline-block; text-align: left;">
  109. ```scheme
  110. [(--> e v)
  111. ----------------------------------
  112. (--> (in-hole E e) (in-hole E v)]
  113. ```
  114. </div>
  115. _Redex uses the notation `(in-hole E e)` to mean an evaluation context `E` with `e` "plugging" the hole `<>`._
  116. </div>
  117. What do evaluation contexts actually have to do with programming language implementation, however? Well, if you squint a bit, and maybe introduce some parameters, evaluation contexts look a lot like what you'd find attached to an operation in...
  118. Continuation-passing Style
  119. --------------------------
  120. I'm not good at structuring blog posts, please bear with me.
  121. Continuation-passing style, also known as <span title="Child protective service- sike!" style="text-decoration: underline dotted">CPS</span>, is a popular intermediate representation for functional language compilers. The goal of CPS is to make evaluation order explicit, and to implement complex control operations like loops, early returns, exceptions, coroutines and more in terms of only lambda abstraction. To achieve this, the language is stratified into two kinds of expressions, "complex" and "atomic".
  122. Atomic expressions, or atoms, are not radioactive or explosive: In fact, they're quite the opposite! The Atoms of CPS are the values of our direct-style language. Forms like `#t`{.scheme}, `#f`{.scheme}, numbers and lambda expressions will not undergo any more evaluation, and thus may appear anywhere. Complex expressions are those that _do_ cause evaluation, such as conditionals and procedure application.
  123. To make sure that evaluation order is explicit, every complex expression has a _continuation_ attached, which here boils down to a function which receives the return value of the expression. Procedures, instead of returning to a caller, will instead tail-call their continuation.
  124. The grammar of our mini Scheme after it has gone CPS transformation is as follows:
  125. <div style="text-align: center;">
  126. <div style="display: inline-block; text-align: left;">
  127. ```scheme
  128. atom ::= (lambda (arg kont) expr) ; continuation argument
  129. | var ; these remain as they were.
  130. | #t | #f
  131. | 1 | 2 | 3 | 4
  132. expr ::= (atom atom atom) ; function, argument, continuation
  133. | (if atom expr expr) ; conditional, then_c, else_c
  134. | atom ; atoms are also valid expressions
  135. ```
  136. </div>
  137. </div>
  138. Note that function application now has _three_ components, but all of them are atoms. Valid expressions include things like `(f x halt)`, which means "apply `f` to `x` such that it returns to `halt`", but do _not_ include `(f (g x y) (h y z))`, which have an ambiguous reduction order. Instead, we must write a &lambda;-abstraction to give a name to the result of each intermediate computation.
  139. For example, the (surface) language application `(e_1 e_2)`, where both are complex expressions, has to be rewritten as either of the following expressions, which correspond respectively to evaluating the function first or the argument first. `(e_1 (lambda r1 (e_2 (lambda r2 (r1 r2))))`{.scheme}
  140. <div class="mathpar">
  141. <div>
  142. ```scheme
  143. (e_1 (lambda r_1
  144. (e_2 (lambda r_2
  145. (r_1 r_2 k)))))
  146. ```
  147. Evaluating the function first
  148. </div>
  149. <div>
  150. ```scheme
  151. (e_1 (lambda r_1
  152. (e_2 (lambda r_2
  153. (r_1 r_2 k)))))
  154. ```
  155. Evaluating the argument first
  156. </div>
  157. </div>
  158. If you have, at any point while reading the previous 2 or so paragraphs, squinted, then you already know where I'm going with this. If not, do it now.
  159. The continuation of an expression corresponds to its evaluation context. The `v`s in our discussion of semantics are the `atom`s of CPS, and most importantly, contexts `E` get closed over with a lambda expression `(lambda x E[x])`{.scheme}, replacing the hole `<>` with a bound variable `x`. Evaluating an expression `(f x)`{.scheme} in a context `E`, say `(<> v)` corresponds to `(f x (lambda x (x v)))`{.scheme}.
  160. If a language implementation uses the same representation for both user procedures and lambda expressions---which is **very** inefficient, let me stress---then we get first-class _control_ for "free". First-class in the sense that control operations, like `return`, can be stored in variables, or lists, passed as arguments to procedures, etc. The fundamental first-class control operator for undelimited continuations is called `call-with-current-continuation`{.scheme}, generally abbreviated to `call/cc`{.scheme}.
  161. <div style="text-align: center;">
  162. <div style="display: inline-block; text-align: left;">
  163. ```scheme
  164. (define call/cc (lambda (f cc) (f cc cc)))
  165. ```
  166. </div>
  167. </div>
  168. Using `call/cc`{.scheme} and a mutable cell holding a list we can implement cooperative threading. The `(yield)` operator has the effect of capturing the current continuation and adding it to (the end) of the list, dequeueing a potentially _different_ saved continuation from the list and jumping there instead.
  169. <div style="text-align: center;">
  170. <div style="display: inline-block; text-align: left;">
  171. ```scheme
  172. (define threads '())
  173. ; Jump to the next thread (read: continuation) or exit the program
  174. ; if there are no more threads to schedule
  175. (define exit
  176. (let ((exit exit))
  177. (lambda ()
  178. (if (null? threads) ; are we out of threads to switch to?
  179. (exit) ; if so, exit the program
  180. (let ((thr (car threads))) ; select the first thread
  181. (set! threads (cdr threads)) ; dequeue it
  182. (thr)))))))) ; jump there
  183. ; Add a function to the list of threads. After finishing its work,
  184. ; the function needs to (exit) so another thread can take over.
  185. (define (fork f)
  186. (set! threads (append threads
  187. (list (lambda () (f) (exit))))))
  188. ; Capture the current continuation, enqueue it, and switch to
  189. ; a different thread of execution.
  190. (define (yield)
  191. (call/cc (lambda (cc)
  192. (set! threads (append threads (list cc)))
  193. (exit))))
  194. ```
  195. </div>
  196. </div>
  197. That's a cooperative threading implementation in 25 lines of Scheme! If whichever implementation you are using has a performant `call/cc`{.scheme}, this will correspond ropughly to the normal stack switching that a cooperative threading implementation has to do.
  198. That last paragraph is a bit of a weasel, though. What's a "performant call/cc" look like? Well, `call/cc`{.scheme} continuations have _abortive_ behaviour[^2], which means they have the effect of _replacing_ the current thread of control when invoked, instead of prepending a segment of stack---which is known as "functional continuations". That is, it's basically a spiffed up `longjmp`{.c}, which in addition to saving the state of the registers, copies the call stack along with it.
  199. However, `call/cc`{.scheme} is a bit overkill for applications such as threads, and even then, it's not the most powerful control abstraction. For one `call/cc`{.scheme} _always_ copies the entire continuation, with no way to *ahem* delimit it. Because of this, abstractions built on `call-with-current-continuation`{.scheme} [do not compose].
  200. [do not compose]: http://okmij.org/ftp/continuations/against-callcc.html
  201. We can fix all of these problems, ironically enough, by adding _more_ power. We instead introduce a _pair_ operators, `prompt` and `control`, which...
  202. Delimit your Continuations
  203. --------------------------
  204. This shtick again?
  205. Delimited continuations are one of those rare ideas that happen once in a lifetime and revolutionise a field---maybe I'm exaggerating a bit. They, unfortunately, have not seen very widespread adoption. But they do have all the characteristics of one of those revolutionary ideas: they're simple to explain, simple to implement, and very powerful.
  206. The idea is obvious from the name, so much that it feels insulting to repeat it: instead of capturing the continuation, have a marker that _delimits_ what's going to be captured. What does this look like in our reduction semantics?
  207. The syntax of evaluation contexts does not change, only the operations. We gain operations `(prompt e)`{.scheme} and `(control k e)`{.scheme}, with the idea being that when `(control k e)` is invoked inside of a `(prompt)` form, the evaluation context from the `control` to the nearest outermost `prompt` is reified as a function and bound to `k`.
  208. <div class="mathpar">
  209. <div>
  210. ```scheme
  211. [-------------------
  212. (--> (prompt v) v)]
  213. ```
  214. Delimiting a value does nothing
  215. </div>
  216. <div>
  217. ```scheme
  218. [----------------------------------------------------------
  219. (--> (prompt (in-hole E (control k body)))
  220. (prompt ((lambda k body) (lambda x (in-hole E x)))))]
  221. ```
  222. Capture the continuation, bind it to the variable `k`, and keep going.
  223. </div>
  224. </div>
  225. By not adding `(prompt E)` to the grammar of evaluation contexts, we ensure that `E` is devoid of any prompts by construction. This captures the intended semantics of "innermost enclosing prompt"---if `E` were modified to include prompts, the second rule would instead capture to the _outermost_ enclosing prompt, and we're back to undelimited call/cc.
  226. Note that `prompt` and `control` are not the only pair of delimited control operators! There's also `shift` and `reset` (and `prompt0`/`control0`). `reset` is basically the same thing as `prompt`, but `shift` is different from `control` in that the captured continuation has the prompt—uh, the delimiter—reinstated, so that it cannot "escape".
  227. <div style="text-align: center;">
  228. <div style="display: inline-block; text-align: left;">
  229. ```scheme
  230. [-----------------------------------------------------------------
  231. (--> (reset (in-hole E (shift k body)))
  232. (reset ((lambda k body) (lambda x (reset (in-hole E x))))))]
  233. ```
  234. Reinstate the prompt when the captured continuation is applied.
  235. </div>
  236. </div>
  237. Yet another pair, which I personally prefer, is what you'd find in Guile's `(ice-9 control)`, namely `(call-with-prompt tag thunk handler)` and `(abort-to-prompt tag value)`. These are significantly more complex than bare `shift` and `reset` since they implement _multi-prompt_ delimited continuations. They're more like exception handlers than anything, with the addded power that your "exception handler" could restart the code after you `throw`{.java}.
  238. <div style="text-align: center;">
  239. <div style="display: inline-block; text-align: left;">
  240. ```scheme
  241. (define-syntax reset
  242. (syntax-rules ()
  243. ((reset . body)
  244. (call-with-prompt (default-prompt-tag)
  245. (lambda () . body)
  246. (lambda (cont f) (f cont))))))
  247. (define-syntax shift
  248. (syntax-rules ()
  249. ((shift k . body)
  250. (abort-to-prompt (default-prompt-tag)
  251. (lambda (cont)
  252. ((lambda (var) (reset . body))
  253. (lambda vals (reset (apply cont vals))))))
  254. ```
  255. `call-with-prompt` and `abort-to-prompt` subsume `shift` and `reset`.
  256. Taken from [the Guile Scheme implementation](https://fossies.org/linux/guile/module/ice-9/control.scm).
  257. </div>
  258. </div>
  259. The operators `call-with-prompt` and `abort-to-prompt` are very convenient for the implementation of many control structures, like generators:
  260. ```scheme
  261. (define-syntax for/generator
  262. (syntax-rules ()
  263. ((_ name gen . body)
  264. (begin
  265. (define (work cont)
  266. (call-with-prompt
  267. 'generator-tag
  268. cont
  269. (lambda (cont name) (begin . body)
  270. (work cont))))
  271. (work gen)))))
  272. (define (yield x) (abort-to-prompt 'generator-tag x))
  273. (for/generator x (lambda ()
  274. (yield 1)
  275. (yield 2)
  276. (yield 3))
  277. (display x) (display #\newline))
  278. ```
  279. Exception handlers and threading in terms of `shift` and `reset` are left as an exercise to the reader.
  280. But... why?
  281. -----------
  282. Control abstractions appeal to our---or at least mine---sense of beauty. Being able to implement control flow operations as part of the language is often touted as one of the superpowers that Haskell gets from its laziness and purity, and while that certainly is true, control operators let us model many, _many_ more control flow abstractions, namely those involving non-local exits and entries.
  283. Of course, all of these can be implemented in the language directly—JavaScript, for example, has `async`/`await`, stackless generators, _and_ exceptions. However, this is not an advantage. These significantly complicate the implementation of the language (as opposed to having a single pair of operators that's not much more complicated to implement than regular exception handlers) while also significantly _diminishing_ its expressive power! For example, using our definition of generators above, the Scheme code on the right does what you expect, but the JavaScript code on the left only yields `20`.
  284. <div class="mathpar">
  285. <div>
  286. ```scheme
  287. ((lambda ()
  288. ((lambda ()
  289. (yield 10)))
  290. (yield 20)))
  291. ```
  292. </div>
  293. <div>
  294. ```javascript
  295. (function*() {
  296. (function*() {
  297. yield 10;
  298. })
  299. yield 20;
  300. })();
  301. ```
  302. </div>
  303. </div>
  304. Delimited continuations can also be used to power the implementation of algebraic effects systems, such as those present in the language Koka, which much lower overhead (both in terms of code size and speed) than the type-driven local CPS transformation that Koka presently uses.
  305. Language implementations which provide delimited control operators can also be extended with effect system support post-hoc, in a library, with an example being the [Eff] library for Haskell and the associated [GHC proposal] to add delimited control operators (`prompt` and `control`).
  306. [Eff]: https://github.com/hasura/eff
  307. [GHC proposal]: https://github.com/ghc-proposals/ghc-proposals/pull/313/
  308. [^1]: In reality it's because I'm lazy and type setting so that it works properly both with KaTeX and with scripting disabled takes far too many keystrokes. Typing some code is easier.
  309. [^2]: People have pointed out to me that "abortive continuation" is a bit oxymoronic, but I guess it's been brought to you by the same folks who brought you "clopen set".