dpg78570 2016-04-24 11:49
浏览 110

Golang yacc生成的解析器的访问结果

I am trying to create a parser using golang's yacc tool. I found nex to simplify creating a lexer to give the parser. My problem now is that the generated parser has no method or field to give me access to the parsing result. I could just store the parse result in a global variable, but that seems wrong.

Currently I've added the following as an initial attempt to the top of my parser.y file:

type ResultParser interface {
  yyParser // Generated parser interface
  Result() s.Expr // s.Expr is an interface for the parsed result
}

func (p *yyParserImpl) Result() s.Expr {
  return p.stack[1].expr
}

func NewResultParser() ResultParser {
  return &yyParserImpl{}
}

Is there a recomended/better way of getting at the result from the parser?
(Since this feels like a bit of an abuse of the generator...)

  • 写回答

2条回答 默认 最新

  • drwj4061 2016-06-23 08:41
    关注

    No, accessing stack[1] does not work reliably. It doesn’t contain any result as soon as the stack needs to grow beyond 16, its initial size. (See #16163.)

    The if statement after the yystack label then creates a new stack and totally forgets about the one saved in yyParserImpl.


    I did the following.

    Add a result field to the lexer type:

    type ShellLexer struct {
        /* … */
        result *ShellProgram
    }
    

    Extend the grammar by the following rule at the very beginning:

    start : program {
        shyylex.(*ShellLexer).result = $$
    }
    

    (This depends on the parameter name of the Parse method (which can have a custom prefix), but I think that’s ok.)

    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题