Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

bison - LEX -YACC parser for infix-to-prefix translation

Translation schemes:

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...