Related articles |
---|
Minimizing parentheses in a postfix->infix converter output acmfiu@fiu.edu (1991-04-13) |
Re: Minimizing parentheses in a postfix->infix converter output ressler@cs.cornell.edu (1991-04-14) |
Re: Minimizing parentheses in a postfix->infix converter output firth@sei.cmu.edu (1991-04-14) |
Re: Minimizing parentheses in a postfix->infix converter output ge@dbf.kun.nl (1991-04-15) |
Newsgroups: | comp.compilers |
From: | ressler@cs.cornell.edu (Gene Ressler) |
Keywords: | design |
Organization: | Cornell Univ. CS Dept, Ithaca NY 14853 |
References: | <9104130521.AA00996@fiu.edu> |
Date: | Sun, 14 Apr 1991 17:28:00 GMT |
In article <9104130521.AA00996@fiu.edu> acmfiu@fiu.edu (ACMFIU) writes:
>I have a postfix->infix converter and need to output the least number of
>parentheses as possible. ...
>
>albert chin
>[It is my recollection that there is an easy way to do paren minimization,
>but the details escape me. Roughly, at each level you build the expression
>string, and wrap a subexpression in parens if its operator binds looser
>than the one in the current expression. -John]
As I recall, something like this is an exercise in the Dragon Book chapter
on syntax-directed translation. John is right. In a SDT, you can pass
down an inherited attribute consisting of the current operator. (In a
tree-walker, of course, this is just a function parameter.) Call this
attribute `parent'. Then each operator's rule looks at `parent' to see if
it should emit `( E op E )', when parent binds tighter than op or just `E
op E', when it doesn't. You also need an inherited attribute `side' that
tells whether the current operator is the left or right (or only) child of
its parent. This allows rules for non-associative operators to
parenthesize their emitted code correctly; e.g. for A * D / (B * C), the
rule for '*' causes parens to be emitted when `*' is the right child of
'/'.
There are other details depending on the language you want to emit, and
other approaches work, too. For instance, if you pass the code itself as
an attribute (rather than emitting a stream), then you can put parens
around everything, but strip them off when the current op binds more
loosely than the child; here you're using synthesized attributes. The
school of hard knocks has convinced me that a the time to write out the
SDT before coding things like this is paid back many-fold. Good luck.
Gene
--
Return to the
comp.compilers page.
Search the
comp.compilers archives again.