Public Group

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

This topic is 2784 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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!

##### Share on other sites
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 on other sites
Using macros for this pretty much guarantees disaster. Why not try using a real parser/lexer?

##### Share on other sites
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 on other sites
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 on other sites
Meh, I just wanted to do it quickly.
ANTLR looks cool, though. Gonna check it out.

1. 1
Rutin
23
2. 2
3. 3
JoeJ
20
4. 4
5. 5

• 29
• 40
• 23
• 13
• 13
• ### Forum Statistics

• Total Topics
631740
• Total Posts
3001964
×