I've been working on an alternative compiler front-end for Python where all syntax is parsed via macros. I'm finally to the point with its development that I can start work on a superset of the Python language where macros are an integral component.
My problem is that I can't come up with a pythonic macro definition syntax. I've posted several examples in two different syntaxes in answers below. Can anyone come up with a better syntax? It doesn't have to build off the syntax I've proposed in any way -- I'm completely open here. Any comments, suggestions, etc would be helpful, as would alternative syntaxes showing the examples I've posted.
A note about the macro structure, as seen in the examples I've posted: The use of MultiLine/MLMacro and Partial/PartialMacro tell the parser how the macro is applied. If it's multiline, the macro will match multiple line lists; generally used for constructs. If it's partial, the macro will match code in the middle of a list; generally used for operators.
If you're only asking about the syntax (not implementation) of macros within Python, then I believe the answer is obvious. The syntax should closely match what Python already has (i.e., the "
def
" keyword).Whether you implement this as one of the following is up to you:
but I believe it should be exactly the same as a normal function with respect to the rest so that:
and
are functionally equivalent.
The way I would implement this is with a pre-processor (a la C) which would:
a
with__macro_second_local_a
.No doubt there'll be some nigglies to take care of (like tuples or multiple return points) but Python is sufficiently robust to handle that in my opinion.
So:
becomes:
This is a new macro syntax I've come up with based on Kent Fredric's ideas. It parses the syntax into a list just like the code is parsed.
Print macro:
If macro:
X to Y [inclusive] [step Z] macro:
Aside from the minor issue of using decorators to identify macro type, my only real issue with this is the way you can name groups, e.g. in the if case. I'm using @name = ..., but this just reeks of Perl. I don't want to just use name = ... because that could conflict with a macro pattern to match. Any ideas?
You should take a look at MetaPython to see if it accomplishes what you're looking for.