Writing a proc/declarative macro that generates code and return a value

I have implemented a proc macro named median!(...) that compiles and return the median of a sequence of integers. e.g.

let median: i32 = median!(1, 2, 3);
assert_eq!(median, 2); // true

It computes the median during the precompilation phase and simply return a quote!(#median) where #median is a syn::LitInt.

My question is:

It seems like there is no way for a proc-macro that does the generation of codes and at the same time, 'returns' a value. Is that true?

I understand proc-macro is like a copy-and-paste facility such that let median = median!(...); is simply expanded to let median = #some_generated_rust_codes;.

1 Like

Seems a duplicate of Passing a reference into a procedural macro in Rust which is answered IMO.

Macros won't compute anything except tokens. I.E. You can't get const evaluation in macros.

Certain forms of expressions, called constant expressions, can be evaluated at compile time. In const contexts, these are the only allowed expressions, and are always evaluated at compile time.


Can you explain what you mean by “at the same time, return a value”? How does the macro you currently have not meet that goal? Obviously your current macro generates code that, when run, returns a value, but if that is not what you want, what do you want? Or concisely: Return a value to what, and when?


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.