home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!stanford.edu!rutgers!faatcrl!iecc!compilers-sender
- From: twpierce@amhux1.amherst.EDU (Tim Pierce)
- Newsgroups: comp.compilers
- Subject: Re: constant folding at parse time
- Keywords: parse, attribute
- Message-ID: <92-08-114@comp.compilers>
- Date: 19 Aug 92 15:53:46 GMT
- References: <92-08-040@comp.compilers> <92-08-097@comp.compilers>
- Sender: compilers-sender@iecc.cambridge.ma.us
- Reply-To: Tim Pierce <twpierce@amhux1.amherst.EDU>
- Organization: Amherst College, Amherst MA
- Lines: 40
- Approved: compilers@iecc.cambridge.ma.us
-
- The discussion about constant folding has intrigued me a little bit, and
- I've been a little stumped figuring out how I would implement this in the
- general case. Writing code into mknode() to fold the addition or
- multiplication of two nodes with constant value makes sense to me, for
- example. But what about an expression such as "4 + y + 4"? As I see it,
- a shift-reduce parser following the rule
-
- expr -> expr + expr
- | CONST
- | ID
-
- would process this expression as follows:
-
- 4 + y + 4
- CONST + y + 4
- expr + y + 4
- expr + ID + 4
- expr + expr + 4
- expr + 4
- expr + CONST
- expr + expr
- expr
-
- At no time does the parser have any inkling that there are two constant
- terms in this expression that can be folded together. In order to encode
- this recognition, I imagine you'd have to fix the parser to rearrange
- terms in some order that would permit constant folding. I've checked the
- dragon book (second edition) but they seemed pretty vague on
- implementation ideas. Any thoughts?
- --
- Tim Pierce, twpierce@amherst.edu, (BITnet: TWPIERCE@AMHERST)
- [The only approach I've seen is pretty much brute force -- when you have a
- subtree with multiple instances of an associative operator, flatten the
- tree into a list, sort the list to put all the constants together,
- collapse the constants, and remake a tree. It is my dim recollection that
- the Ritchie PDP-11 compiler actually did this, because you can get
- significant savings in some kinds of addressing expressions. -John]
- --
- Send compilers articles to compilers@iecc.cambridge.ma.us or
- {ima | spdcc | world}!iecc!compilers. Meta-mail to compilers-request.
-