Re: Display a parse tree with minimum parentheses?

Clint Olsen <clint@0lsen.net>
15 Apr 2004 12:30:19 -0400

          From comp.compilers

Related articles
Display a parse tree with minimum parentheses? johnmillaway@yahoo.com (John Millaway) (2004-04-14)
Re: Display a parse tree with minimum parentheses? danwang74@hotmail.com (Daniel C. Wang) (2004-04-15)
Re: Display a parse tree with minimum parentheses? haberg@matematik.su.se (2004-04-15)
Re: Display a parse tree with minimum parentheses? clint@0lsen.net (Clint Olsen) (2004-04-15)
| List of all articles for this month |
From: Clint Olsen <clint@0lsen.net>
Newsgroups: comp.compilers
Date: 15 Apr 2004 12:30:19 -0400
Organization: Comcast Online
References: 04-04-034
Keywords: parse, tools
Posted-Date: 15 Apr 2004 12:30:19 EDT

On 2004-04-14, John Millaway <johnmillaway@yahoo.com> wrote:
> For example, the parse tree for the expression, "a or b and c," would be
> naively printed as "(a or (b and c))," although no parentheses are
> required, assuming that the `and' operator has higher precedence than the
> `or' operator.
>
> My best guess is that the the left subtree requires parentheses if the
> precedence of the right-most unparenthesized operator in that subtree is
> less than or equal to the precedence of the current operator, and
> similarly for the right subtree.


Yes, I've implemented something similar to this in some language
translators where the languages have differing operator precedences. The
parse tree reflects the appropriate precedence for the source language, and
as you do the tree walk, you can check to see if the precedence of the
current operator is less than (rather than less than or equal to) the
parent operator. You know this to be true since the precedence of the
operators generally increase as you descend in the tree - barring
precedence override operators like parens.


Your algorithm is going to be similar except you'll have the proviso that
you'll be at the operator '()' and you'll want to check the parent operator
against the operator of it's child. If the child operator precedence is
less than the parent operator, then the parens were necessary. Otherwise,
prune the parens out of the tree. You can also short circuit redundant
parentheses by checking the last operator against the current one.


-Clint


Post a followup to this message

Return to the comp.compilers page.
Search the comp.compilers archives again.