First of all see of course the docs here:

[https://nim-lang.github.io/Nim/macros.html#quote%2Ctyped%2Cstring](https://nim-lang.github.io/Nim/macros.html#quote%2Ctyped%2Cstring)

and the macro tutorial, specifically:

[https://nim-lang.github.io/Nim/tut3.html#introduction-generating-code](https://nim-lang.github.io/Nim/tut3.html#introduction-generating-code)

So the basic idea is that quote do allows you to write exactly the code you 
want to generate. However, in most cases that's not really very helpful, 
because if you can explicitly write your code, you could also just write a 
template / proc. That's where the back ticks come in to perform actual quoting 
of NimNodes defined in the current scope. They will be inserted in those places.

quote do is thus just a nice way to avoid having to build the AST manually (as 
I for instance do in the newVar proc), but keep the ability to insert NimNodes 
you calculate / determine somehow based on what the macro is supposed to 
accomplish.

Another thing to keep in mind when using quote do is about the stuff that's not 
quoted with back ticks. As a rule of thumb (someone please correct me):

  * any procedure / template you use within quote do will be bound in the scope 
where the macro code is injected
  * any variables you introduce will be "gensym'd", that is for each symbol you 
introduce a unique symbol will be created. So if you write var x = 5 within 
quote do, the final code won't have the variable x, but something like x_12345.



The second means that if you want to refer to some variable that will be known 
in the scope in which the macro is used, you have to create the identifier 
manually and quote it. Due to the first point you fortunately don't have to do 
the same for procedures you want to use.

Reply via email to