Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...