0

I'm working on a DSL implemented as a proc macro, and would like to be able to get to the original source, as a string, of the contents of the proc macro.

So for instance, if my proc macro is invoked like so:

my_macro! {
one
two
three
}

I would like to get access to this string inside the proc macro implementation:

let source: String = get_source(input) // this is what I want to be able to do

println!("{}", source);
// prints: "one\ntwo\nthree"

I can't figure out how to do this. When I try to convert the token stream to a string, the whitespace information is lost.

So for instance if I try to convert the token stream directly to a string, each token is simply separated by a space:

#[proc_macro]
pub fn my_macro(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    
    println!("{}", input);
    // prints "one two three"

...

How can I get the input source?

sak
  • 2,612
  • 24
  • 55
  • 1
    You could use the unstable methods `start` and `end` on `Span` to get the line and column number. That would allow you to recover whitespace. I've seen this used once for parsing whitespace sensitive languages or sth like that. – Lukas Kalbertodt Oct 07 '22 at 08:57
  • 1
    You might want to [edit] your question to add your use case. This looks like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – the busybee Oct 07 '22 at 09:31
  • It's not an XY problem I can assure you. I gave a concrete example. – sak Oct 07 '22 at 10:52

0 Answers0