亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

解析右結合運算符(指數)

解析右結合運算符(指數)

海綿寶寶撒 2021-06-03 14:09:23
我一直在為我自己的語言編寫詞法分析器/解析器/解釋器,到目前為止一切都在工作。我一直在關注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.我可以嘗試的任何方法?
查看完整描述

1 回答

  • 1 回答
  • 0 關注
  • 149 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號