首先需要参考Ecma-262文档中的附录A.3Expression中的产生式,v8中的代码是据此进行语法分析的,它采用的算符优先的语法分析方法,在token.h中给出了各种算符的precedence,关于算符优先算法,wiki中给出如下的伪代码
http://en.wikipedia.org/wiki/Operator-precedence_parser
parse_expression ()
return parse_expression_1 (parse_primary (), 0)
parse_expression_1 (lhs, min_precedence)
while the next token is a binary operator whose precedence is >= min_precedence
op := next token
rhs := parse_primary ()
while the next token is a binary operator whose precedence is greater
than op's, or a right-associative operator
whose precedence is equal to op's
lookahead := next token
rhs := parse_expression_1 (rhs, lookahead's precedence)//这里递归,当前token指向rhs,lookahead下一个token的优先级以后才能确定是否递归,所以在进入递归后,一定能保证第一个循环时next token的优先级大于等于参数指定的优先级
lhs := the result of applying op with operands lhs and rhs
return lhs
这里需要介绍两个术语lhs(left hand side),rhs(right hand side),分别表示左操作数和右操作数。该算法简而言之,就是比较算符的优先级,如果后出现的算符的优先级更高,那么就继续递归,否则就计算结果,并把结果作为左操作数继续循环。
解析V8引擎的算符优先语法分析方法

本文详细解读了V8引擎如何通过算符优先算法进行语法分析,包括解析过程、核心概念(如lhs、rhs)及具体实现细节。通过深入探讨,读者能更好地理解JavaScript引擎的工作原理。
754

被折叠的 条评论
为什么被折叠?



