How To Build a Yacc?(14)

既然已经生成了DFA,按照之前的描述写出shift_reduction算法就不是什么了不起的工作了。

class Compiler
  def initialize(rule_file, src_file)
    @yacc = Yacc.new(rule_file)
    @lex = ExtendLex.new(src_file)
    @parse_stack = Array.new
  end
 
  def run
    @yacc.generate
    shift_reduction
  end

 
  def shift_reduction
    @parse_stack.push(0)
    token = @lex.get_next_token2
    while true          
      action = @yacc.dfa.action(@parse_stack.last, token)     
      return false until action
      action_id = action[0]
      new_state = action[1]
      case action_id
        when DFA::SHIFT
          @parse_stack.push(token)
          @parse_stack.push(new_state)
          token = @lex.get_next_token2
        when DFA::REDUCE
          rule = new_state[0].rule
          eval(rule.action)
          # pop 2 * rt.length
          rindex = 0 - 2 * rule.rt.length
          @parse_stack[rindex..-1] = nil
          goto = @yacc.dfa.action(@parse_stack.last, rule.lt)
          if goto
            if goto[0] == DFA::SHIFT            
              @parse_stack.push(rule.lt)
              @parse_stack.push(goto[1])
            elsif goto[0] == DFA::ACCEPT
              return true
            end
          else
            return false
          end
        when DFA::ACCEPT
          return true       
      end
    end
  end
 
end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值