What will happen if the AST generated by a macro is obviously artificial or unnatural (that will never come from the code parser)?
For example,
Infix
Ident "*"
Infix
Ident "+"
IntLit 1
IntLit 2
IntLit 3
Is it still vaild?
Why wouldn't your example be valid? The compiler checks the AST after macro expansion, it can reject it and produce an error message.
To be honest, I doubt I understood your question.
Because
1 + 2 * 3
will become
Infix
Ident "+"
IntLit 1
Infix
Ident "*"
IntLit 2
IntLit 3
or alike, while
(1 + 2) * 3
becomes
Infix
Ident "*"
Par
Infix
Ident "+"
IntLit 1
IntLit 2
IntLit 3
or alike.
There's no way to form the AST I provided in the first post, except by using a macro to generate it artificially, so I said it's "artificial" or "unnatural." But I'm not sure if it's wrong.
Why not try it? Here's example implementation:
import std/[macros]
macro foo(): untyped =
result = newStmtList(
infix(
newLit(1),
"*",
infix(
newLit(2),
"+",
newLit(3)
)
)
)
echo result.repr # this line will print the code generated by a macro at compile time
echo foo()
Here's the code generated by the macro:
1 * (2 + 3)
Output is obviously - 5
I hope this answers your question.