Since C2 wants to avoid the pitfalls of the C textual-replacement based macro system (and C2 doesn't have includes), a replacement macro system is needed.
Macros have a various, valid use-cases. I'll focus on one case here and try to find a nice syntax + semantics.
What I want is to be able to put a loop over a data structure in a macro, so that changing the underlying data structure maybe doesn't need any 'api' change
for users. So something like
(in some function)
// there is a list.List* mylist that points to the list (let's say a linked-list)
list.foreach(mylist, i) { // i is the name of the Element*
// use Element* i here
if (i.value == 10) break;
}
So:
- list.foreach is the macro
- When changing the data structure from a linked list to a vector, nothing much has to change in the fragment.
- The break statement should break out of the macro loop even if the macro itself has multiple, nested loops.
Note that this is generally not possible in C, since the macro probably needs to add code
before and
after the user code inside the loop.
The definition could be roughly something like:
public macro foreach(List* thelist, iname) {
Element* iname = thelist.first;
while (iname != nil) {
// macro body should be here, How to specify?
iname = iname.next;
}
}
So this brings up a lot of questions:
- how to let a user specify the name of the iterator?
- Do we required types for macro arguments?
- How can we specify the place for the macro body?
- Do we allow using variables from the calling scope (and how to specify)
- How can we implement the break in user code
- Do we allow nested macro calling?
For C macro's all these questions are easy, since it's just replacing text. But that gives rise to a lot of issues, so a new system
is definitely needed. But I think a non-textual system will have a lot more restrictions (which can be good), so when designing a
new system, the goal should not be to find a replacement for
every possibility in C macros. This won't work. My plan is to
start creating a set of use-cases and build on top of that. The foreach example is just one of those use-cases.