tags:

views:

35

answers:

1

What is the easiest (or the best) way to implement macro definitions in ANTLR? What I want is a mechanism similar to the one that is present in C/C++ language:

#define FUNCTION(a, b) a+b
#define PI 3.1415

How and when should I perform replacement?

+1  A: 

If you are doing a pre-processor in the style of C, then you will want to do a separate first pass for pre-processing (which is what this term means - a processing pass before your standard lex/parse pass).

Exactly how you want to do the pass is up to you - you can pass your input text to one grammar in antlr, take the result and hand that off to another grammar, etc.

Or you can create separate programs, which are able to take input on stdin and output to stdout, or pass text between pipes, etc.

Once you have that worked out, its a simple matter of looking for your keywords. Check every token that you see against your table of #defines, and if it matches, replace it with the definition that you have. You will also have to be able to parse function parameters, but that shouldn't add too much effort.

a_m0d