v8::internal::Parser中的Expression解析

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

該算法在Parser::ParseBinaryExpression函數(定義於parser.cc)中得到了充分的體現,該函數主要用於二元表達式和條件表達式的分析,其中遞歸調用了ParseBinaryExpression函數,且傳入的precedence在當前操作符基礎上加一,這是因爲這裏的二元操作符都是左結合的,在相同優先級情況下,左邊的操作符的優先級要高
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章