首先需要參考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),分別表示左操作數和右操作數。該算法簡而言之,就是比較算符的優先級,如果後出現的算符的優先級更高,那麼就繼續遞歸,否則就計算結果,並把結果作爲左操作數繼續循環。