LEX -YACC解析器,用于从前缀到前缀的转换 [英] LEX -YACC parser for infix-to-prefix translation

查看:124
本文介绍了LEX -YACC解析器,用于从前缀到前缀的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

翻译方案:

expr -> {print("+")} expr + term
      | {print("-")} expr - term
      | term
term -> {print("*")} term * factor
      | {print("/")} term / factor
      | factor
factor -> digit {print(digit)}
        | (expr)

以上语法将以前缀形式打印表达式.对于此语法,无法编写解析器. 我们如何编写lex和yacc程序将中缀转换为前缀. 我遵循此 lex和yacc程序将中缀转换为前缀但没有得到正确的输出.任何想法如何编写解析器.

Above grammar will print the expression in prefix form. For this grammar it is not possible to write the parser. how could we write the lex and yacc program to convert infix to prefix. I follow this lex and yacc program to convert infix to prefix but not getting proper output. Any idea how to write the parser.

推荐答案

由于只有在使用运算符减少规则(识别它们)之后才能输出运算符,因此需要在表达式之前保存表达式的字符串.运算符(而不是像看到的那样输出),以便可以在运算符后 发出它.这意味着您的规则需要使用翻译构建字符串,并且仅在解析完整的表达式后才输出字符串.

Since you can't output operator tokens until after you reduce rules with them (recognize them), you'll need to save the string for the expression before the operator (rather than outputting it as you see it) so it can be emitted after the operator. This means that your rules need to build strings with the translation and only output the string only after parsing a complete expression.

有多种方法可以在C中构建字符串.您可以使用asprintfmalloc + strcpy/strcat/sprintf,然后担心何时适当释放内容.或者,您可以使用某种字符串池为您跟踪内存并进行清理.

There are a number of ways of building strings in C. You can use asprintf or malloc + strcpy/strcat/sprintf, and then worry about when to properly free stuff afterwards. Or you can use some sort of string pool that tracks the memory for you and can deal with cleanup.

这篇关于LEX -YACC解析器,用于从前缀到前缀的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆