[C++] Can I do this with macros?

Started by
4 comments, last by HeresJohnny 13 years, 4 months ago
I'm trying to develop a simple language using C++ as the host language.
Example:
canvas (100, 100)circle (10, 10) radius 5square (10, 10), (40,40)


But I'm having problems with the "square" syntax. I'm not sure how to write a macro that could grok ", (40,40)".
I've tried using the following macro:
#define square(x, y, w, h) Square* sqr = new Square(x,y,w,h);

but it just gets the first pair values and doesn't know how to get to the other pair values.

Is there a way I can manipulate the code written so I could transform it from
square (10, 10), (40,40)
to
square (10, 10, 40, 40)
before compiling it? Even if I could just insert code between the two pair value, that would be great! Is it possible, though?

Note that I cannot change the syntax of the simple language, as that would break the spec.

Thanks!
Advertisement
I would discourage this. How will you be sanitizing the code to not expose any exploit one can think of?

My advise would be to learn about basic compiler construction, there's many tutorials on the web. Very simple compilers are not even hard to write, once you made it past the first basic steps (if you begin now, there's a chance that you finish your first toy language in a few hours).
Using macros for this pretty much guarantees disaster. Why not try using a real parser/lexer?
I trust exceptions about as far as I can throw them.
Or write your own lexical parser! It's not that difficult, really...

- Load file into memory (perhaps one abstraction that actually loads it in pieces, but provides access as if continuous).
- Go over it, per character determine the combination of rules that gives the greatest span. For example, one rule might be that numbers are 0-9 for n characters long. This happens to be the rule that gave the largest number of characters covered. Syntax errors pop here.
- Put these into a token tree, a (linked?) list of small structs telling what kind of token it is and it's content (like the Number token, containing the number itself).
- Parse it by meaning, semantic errors go here.
- Execute it.

Sorry if this wasn't what you want to hear. Using macro's is just hell though, they are way too limited. They should either leave macro's out, or extend them heavily. But that put aside.


Why not put: square (p(10, 10), p(40, 40)), with p for point or something.
[size="2"]SignatureShuffle: [size="2"]Random signature images on fora
Look in to Boost::Spirit for creating your parser. Macros are really nasty and have so many faults. Also if you are newing in your macro, how you going to delete it?
Meh, I just wanted to do it quickly.
ANTLR looks cool, though. Gonna check it out.

This topic is closed to new replies.

Advertisement