中文版第 78 页的一个关键错误:
来看一个例子,假设正在解析表达式语句
-1+2;…这里将
PREFIX作为优先级传递给parseExpression,将PREFIX变成了这个parseExpression调用的右约束能力。根据定义PREFIX的优先级很高。结果是parseExpression(PREFIX)不会解析-1中的1,而会将其传递给另一个infixParseFn。在这种情况下,precedence < p.peekPrecedence()一直为false,即infixParseFn不会将1作为表达式的左半边,而是将1作为前缀的“右半边”返回。这个右半边只有一个1,没有随后需要解析的其他表达式。
找来原文:
This passes
PREFIXto parseExpression as precedence, turningPREFIXinto the right-binding power of that parseExpression invocation.PREFIXis a really high precedence, as per our definition. The result of this is thatparseExpression(PREFIX)is never going to parse the1in-1and pass it to anotherinfixParseFn. Theprecedence < p.peekPrecedence()will never be true in this case, meaning that no otherinfixParseFnis going to get our1as the left arm. > Instead the1is returned as the “right” arm of our prefix expression. Just the1, not some other expression that comes after and needs to be parsed.
其中这句
The result of this is that
parseExpression(PREFIX)is never going to parse the1in-1and pass it to anotherinfixParseFn.
原文表述有歧义,而中文版则完全没有理解 Pratt 解析器的工作原理,翻译错误。这句话是理解 Pratt 工作原理最重要的一句。
更准确的英文表述应该是什么?
The result of this is that, although parseExpression(PREFIX) does parse the 1 in -1, it will never pass that 1 to another infixParseFn as the left-hand side of an infix expression.
所以更准确的中文:
结果是,parseExpression(PREFIX) 会解析 -1 中的 1,但不会将其传递给另一个 infixParseFn。因为在这种情况下,precedence < p.peekPrecedence() 一直为 false,不会有 infixParseFn 将 1 作为表达式的左半边。而是会跳过循环,将 1 返回,成为前缀的“右半边”。这个右半边只有一个 1,没有随后需要解析的其他表达式。