Sign in to follow this  

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

Recommended Posts

HeresJohnny    100
I'm trying to develop a simple language using C++ as the host language.

canvas (100, 100)
circle (10, 10) radius 5
square (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)
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.


Share this post

Link to post
Share on other sites
phresnel    953
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).

Share this post

Link to post
Share on other sites
Decrius    100
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.

Share this post

Link to post
Share on other sites
SeaBourne    120
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?

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this