我一直在為我自己的語言編寫詞法分析器/解析器/解釋器,到目前為止一切都在工作。我一直在關注Ruslan Spivak 博客上的示例(每篇文章的Github鏈接)。我想延長我的語言語法過去所寫的文章,包括更多的運營商喜歡攀比(<,>=,等),也指數(**或^在我的語言)。我有這個語法:expression : exponent ((ADD | SUB) exponent)*exponent : term ((POWER) term)*# this one is right-associative (powers **)term : comparison ((MUL | DIV) comparison)*comparison : factor ((EQUAl | L_EQUAL | LESS N_EQUAL | G_EQUAL | GREATER) factor)*# these are all binary operationsfactor : NUM | STR | variable | ADD factor | SUB factor | LPAREN expr RPAREN# different types of 'base' types like integers# also contains parenthesised expressions which are evalutaed first在解析tokens方面,我使用的方法與Ruslan的博客中使用的方法相同。這是一個將解析該exponent行的行,盡管它的名稱處理加法和減法,因為語法說表達式被解析為 exponent_expr (+ / -) exponent_exprdef exponent(self): node = self.term() while self.current_token.type in (ADD, SUB): token = self.current_token if token.type == ADD: self.consume_token(ADD) elif token.type == SUB: self.consume_token(SUB) node = BinaryOperation(left_node=node, operator=token, right_node=self.term()) return node現在這可以很好地解析左關聯標記(因為標記流自然地從左到右),但我堅持如何解析右關聯指數??纯催@個預期的輸入/輸出以供參考:>>> 2 ** 3 ** 2# should be parsed as...>>> 2 ** (3 ** 2)# which is...>>> 2 ** 9# which returns...512# Mine, at the moment, parses it as...>>> (2 ** 3) ** 2# which is...>>> 8 ** 2# which returns...64為了解決這個問題,我嘗試切換BinaryOperation()構造函數的左右節點,使當前節點成為右邊,新節點成為左邊,但這只會使2**5parse as5**2給出我25而不是預期的32.我可以嘗試的任何方法?
添加回答
舉報
0/150
提交
取消