Crystal: Can you pass Operators to Macro's?

Created on 13 Jun 2018  路  2Comments  路  Source: crystal-lang/crystal

E.G.

macro test(a,b,operator)
  {{a}}{{operator}}{{b}}
end
test 1, 2, +

Testing this code will throw a syntax error Syntax error in eval:4: unexpected token: EOF

Alternatively when sending a symbol:

macro test(a,b,operator)
  {{a}}{{operator}}{{b}}
end
test 1, 2, :+

Crystal throws a Error in line 4: macro didn't expand to a valid program, it expanded to... error because it expanded to 1:+2, which isn't correct for obvious reasons.

Can we convert an ASTNode into a literal or something along those lines?

question

Most helpful comment

Using a symbol is a good solution, but you need to expand it not as a symbol but as an operator using {{ operator.id }}.

macro test(a,b,operator)
  {{a}}{{operator.id}}{{b}}
end
test 1, 2, :+

All 2 comments

Macros arguments needs to be valid AST nodes. Sometimes you will be able to change the meaning of the node during the expansion of the macros. But for binary operators that is not possible since + is not valid expression as a whole.

FYI: this is better in stackoverflow

Using a symbol is a good solution, but you need to expand it not as a symbol but as an operator using {{ operator.id }}.

macro test(a,b,operator)
  {{a}}{{operator.id}}{{b}}
end
test 1, 2, :+
Was this page helpful?
0 / 5 - 0 ratings

Related issues

straight-shoota picture straight-shoota  路  91Comments

fridgerator picture fridgerator  路  79Comments

MakeNowJust picture MakeNowJust  路  64Comments

HCLarsen picture HCLarsen  路  162Comments

chocolateboy picture chocolateboy  路  87Comments