Re: HELP: Using an abstract syntax tree for semantic checking

Jake Donham <donham@linex.com>
7 May 1998 17:02:08 -0400

          From comp.compilers

Related articles
HELP: Using an abstract syntax tree for semantic checking nealh@dinigroup.com (Neal Harder) (1998-05-04)
Re: HELP: Using an abstract syntax tree for semantic checking chase@naturalbridge.com (David Chase) (1998-05-07)
Re: HELP: Using an abstract syntax tree for semantic checking dwight@pentasoft.com (1998-05-07)
Re: HELP: Using an abstract syntax tree for semantic checking rod.bates@wichita.boeing.com (Rodney M. Bates) (1998-05-07)
Re: HELP: Using an abstract syntax tree for semantic checking thetick@magelang.com (1998-05-07)
Re: HELP: Using an abstract syntax tree for semantic checking donham@linex.com (Jake Donham) (1998-05-07)
Re: HELP: Using an abstract syntax tree for semantic checking ndc@alum.mit.edu (N. D. Culver) (1998-05-07)
Re: HELP: Using an abstract syntax tree for semantic checking adrian@dcs.rhbnc.ac.uk (1998-05-07)
Re: HELP: Using an abstract syntax tree for semantic checking danwang+news@CS.Princeton.EDU (Daniel C. Wang) (1998-05-12)
Re: HELP: Using an abstract syntax tree for semantic checking cfc@world.std.com (Chris F Clark) (1998-05-12)
| List of all articles for this month |

From: Jake Donham <donham@linex.com>
Newsgroups: comp.compilers
Date: 7 May 1998 17:02:08 -0400
Organization: DNAI ( Direct Network Access )
References: 98-05-004
Keywords: analysis, question, OOP

"Neal" == Neal Harder <nealh@dinigroup.com> remarks:


        Neal> I realize that this could be accomplished simply by
        Neal> traversing the parse tree and calling functions based on a
        Neal> gigantic switch statement (In which the token value of the
        Neal> node in the parse tree is used to decide which function(s)
        Neal> should be called) - but with hundreds of rules, this is
        Neal> rather ugly and inefficient. My current approach is to
        Neal> write a function for each rule in the grammar.


Check out the Interpreter and Visitor patterns in Design Patterns by
Gamma et al. The basic idea is to have a class for each rule, and an
object of the corresponding class for each node of the parse tree. You
either write the "gigantic switch" as a virtual method on each class
(Interpreter pattern), or write a generic visit() method that applies
a function to the parts of an object, and pass the switch as a visitor
(Visitor pattern). You might also check out the Singleton and Flywheel
patterns, which can be handy for keeping the parse tree from sucking
too much memory.


I've found this to be a nice way to keep things clean; it's easy to
drop in a new syntax class to implement a new piece of syntax. On the
other hand, if your syntax is relatively fixed, it's easy to drop in
new compiler passes by creating a new visitor.


Jake
--


Post a followup to this message

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