The Magic of Partial Evaluation
本文为原文前 6,000 字符的节选翻译,完整内容请查看原文。
The Magic of Partial Evaluation
There are certain ideas in software that are simply beautiful. It doesn’t matter if they have any practical use. It doesn’t matter that you will never convince your coworkers to consider them. There is just something captivating about the way some computational systems work.
软件领域中存在一些极其优美的思想。它们是否有实际用途并不重要,你是否能说服同事去考虑它们也不重要。某些计算系统的工作方式就是有一种令人着迷的特质。
For me, the most beautiful pieces of software are those that reveal something about the nature of programming languages. Programming languages are my obsession. I have never met a problem that couldn’t be solved by introducing yet another programming language. Solving a problem at the programming language level is about solving the meta problem.
对我而言,最美的软件是那些揭示了编程语言本质的软件。编程语言是我的执念。我从未遇到过无法通过引入另一种编程语言来解决的问题。在编程语言层面解决问题,实际上是在解决元问题。
Instead of trying to solve a particular problem, we take a step back and ask how we can solve a whole class of problems at once. So when I find something that makes me rethink the nature of programming languages, I start rethinking computation as a whole. One of these incredibly beautiful but tricky concepts goes by the name partial evaluation.
我们不再试图解决某个特定的问题,而是退后一步,思考如何一次性解决一整类问题。因此,当我发现某些东西让我重新思考编程语言的本质时,我便开始重新思考整个计算过程。这些极其优美但又棘手的概念之一,被称为“偏求值”(partial evaluation)。
If you are fascinated by interpreters and compilers, partial evaluation will teach you how they are related, and how you can get a compiler for free.
如果你对解释器和编译器着迷,偏求值将教会你它们之间的联系,以及如何免费获得一个编译器。
Partial Evaluation Easy Mode
偏求值简易模式
Partial evaluation has been a fascination of mine for a while. But this whole thing came up when James Long announced he had revived Meta’s partial evaluator for JavaScript called prepack. When I first heard about prepack, I had some high hopes and expectations for the project, but was sadly let down. This revival brought to light those same dreams.
偏求值一直是我着迷的话题。这一切始于 James Long 宣布他复活了 Meta 为 JavaScript 开发的偏求值器 Prepack。当我第一次听说 Prepack 时,我对该项目寄予厚望,但最终却感到失望。这次复活让那些梦想重见天日。
But sadly, just as with the original aim, prepack was not designed for beauty, but for practicality. So I figured it was time to renew my own efforts. Yes, in some ways this is a post repping my own library I’m releasing. But I’m not doing this because I want it to be used. I’m doing this because it lets you play with the idea I find so beautiful. That is what this post is about.
但遗憾的是,正如其最初的目标一样,Prepack 的设计初衷并非为了优美,而是为了实用。所以我认为现在是时候重新投入我自己的努力了。是的,在某种程度上,这篇文章是在宣传我即将发布的库。但我这样做并不是为了让它被广泛使用,而是因为它能让你体验我所认为的那种优美思想。这就是本文的主旨。
Doing Partial Evaluation by Hand
手动进行偏求值
Consider the following code:
function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
factorial(5);
考虑以下代码:
function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
factorial(5);
As a person who reads code, you can think about how this code computes and what answer it will give. But you can do more than just give the answer. You can see the expanded form of this particular code for these particular calls. This code is spiritually the same as the following expression, once we expand it out.
5 * (4 * (3 * (2 * 1)))
作为一名代码阅读者,你可以思考这段代码是如何计算的以及它会给出什么答案。但你不仅能给出答案,还能看到这段特定代码在特定调用下的展开形式。一旦展开,这段代码在逻辑上与以下表达式是相同的:
5 * (4 * (3 * (2 * 1)))
In this case, there is really nothing at all that this code needs to do at runtime. A sufficiently smart compiler will just run this code directly at compile time and give the answer. But this is a bit less clear if things come in at runtime.
function power(base, exponent) {
if (exponent === 0) return 1;
return base * power(base, exponent - 1);
}
power(process.argv[2], 5)
在这种情况下,代码在运行时根本不需要做任何事情。一个足够聪明的编译器会在编译时直接运行这段代码并给出答案。但如果某些内容是在运行时传入的,情况就不那么明朗了。
function power(base, exponent) {
if (exponent === 0) return 1;
return base * power(base, exponent - 1);
}
power(process.argv[2], 5)
It might seem like we can’t do anything here, but again, if you are used to thinking about how programs run, you can trace this out and realize this is just the same as:
process.argv[2] * (process.argv[2] * (process.argv[2] * (process.argv[2] * (process.argv[2] * 1))))
看起来我们在这里无能为力,但如果你习惯于思考程序的运行方式,你就可以推导并意识到这等同于:
process.argv[2] * (process.argv[2] * (process.argv[2] * (process.argv[2] * (process.argv[2] * 1))))
What we have done in both of these cases is called partial evaluation. In the first, it was a trivial case because everything was statically known. But in this latter case, we have reduced a program down into the essentials of its dynamic structure. There are no recursive function calls left. All of this has been expanded as far as it could till we get just the dynamic parts of the code remaining.
我们在上述两种情况下所做的就是所谓的“偏求值”。第一种情况很简单,因为一切都是静态已知的。但在后一种情况下,我们将程序简化为其动态结构的核心要素。递归函数调用消失了,所有内容都被尽可能地展开,直到只剩下代码的动态部分。
The Big Idea
核心思想
This intuitive notion of partial evaluation is all you need to know to appreciate the beauty here. Partial evaluation just evaluates the part of the program we can evaluate at build time and leaves all the rest. When we do this with certain programs in certain combinations, we get some quite surprising, incredible behavior.
这种关于偏求值的直观概念,足以让你领略其中的美感。偏求值只是在构建时对程序中可求值的部分进行计算,而保留其余部分。当我们以特定的组合对某些程序进行这种操作时,会产生一些令人惊讶且不可思议的行为。
function calculate(expr) {
if (typeof expr === "number") return expr;
switch (expr[0]) {
case "+": return calculate(expr[1]) + calculate(expr[2]);
case "-": return calculate(expr[1]) - calculate(expr[2]);
case "*": return calculate(expr[1]) * calculate(expr[2]);
case "/": return calculate(expr[1]) / calculate(expr[2]);
default: throw new Error("Unknown operator");
}
}
calculate(["+", 1, ["*", 2, 3]]);
function calculate(expr) {
if (typeof expr === "number") return expr;
switch (expr[0]) {
case "+": return calculate(expr[1]) + calculate(expr[2]);
case "-": return calculate(expr[1]) - calculate(expr[2]);
case "*": return calculate(expr[1]) * calculate(expr[2]);
case "/": return calculate(expr[1]) / calculate(expr[2]);
default: throw new Error("Unknown operator");
}
}
calculate(["+", 1, ["*", 2, 3]]);
Here we have a very simple interpreter for a language that just supports arithmetic. For the above expression, you should be able to think about how we could start “partially” evaluating it. (In this case, it can be a full evaluation.) If this kind of partial evaluation isn’t quite clicking for you, I’ve put the steps below to hopefully help it make sense.
这里有一个非常简单的解释器,用于支持算术运算的语言。对于上述表达式,你应该能想到我们如何开始“偏”求值。(在这种情况下,它可以是完全求值。)如果这种偏求值的概念对你来说还不够清晰,我在下面列出了步骤,希望能帮助你理解。
calculate(["+", 1, ["*", 2, 3]]) → calculate(1) + calculate(["*", 2, 3]) → 1 + calculate(["*", 2, 3]) → 1 + (calculate(2) * calculate(3)) → 1 + (2 * calculate(3)) → 1 + (2 * 3) → 1 + 6 → 7
calculate(["+", 1, ["*", 2, 3]]) → calculate(1) + calculate(["*", 2, 3]) → 1 + calculate(["*", 2, 3]) → 1 + (calculate(2) * calculate(3)) → 1 + (2 * calculate(3)) → 1 + (2 * 3) → 1 + 6 → 7
This is a simple evaluation of the code. But what happens if we throw a value we don’t know into the expression?
calculate(["+", Number(process.argv[2]), ["*", 2, 3]]) → ... → Number(process.argv[2]) + 6
这是代码的简单求值。但如果我们向表达式中传入一个未知的值会怎样呢?
calculate(["+", Number(process.argv[2]), ["*", 2, 3]]) → ... → Number(process.argv[2]) + 6
Here we can see that clear partial evaluation difference. We don’t know how to evaluate Number(process.argv[2]). We have no idea what the answer to that will be. But as part of this process, we do know some partial information about it. For example, when we get to if (typeof expr === “number”) return expr; we know that Number(process.argv[2]) is indeed a number. So we can partially evaluate it further.
在这里,我们可以清楚地看到偏求值的不同之处。我们不知道如何计算 Number(process.argv[2]),也不知道它的结果是什么。但作为该过程的一部分,我们确实知道关于它的一些部分信息。例如,当我们执行到 if (typeof expr === "number") return expr; 时,我们知道 Number(process.argv[2]) 确实是一个数字。因此,我们可以进一步对其进行偏求值。
Hopefully this is all making sense. But if you are like me, this all might seem a bit trivial and uninteresting. So let’s look at a more complicated example.
function brainfuck(code, input = "") {
const tape = new Uint8Array(30000);
const jumps = {}, stack = [];
let pointer = 0, inputPointer = 0, output = "";
for (let i = 0; i < code.length; i++) {
if (code[i] === "[") stack.push(i);
if (code[i] === "]") { const start =
希望这一切都讲得通。但如果你和我一样,可能会觉得这一切有点琐碎且无趣。那么让我们来看一个更复杂的例子。
function brainfuck(code, input = "") {
const tape = new Uint8Array(30000);
const jumps = {}, stack = [];
let pointer = 0, inputPointer = 0, output = "";
for (let i = 0; i < code.length; i++) {
if (code[i] === "[") stack.push(i);
if (code[i] === "]") { const start =