Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string into TokenStream

Given a string (str), how can one convert that into a TokenStream in Rust?

I've tried using the quote! macro.

let str = "4";
let tokens = quote! { let num = #str; }; // #str is a str not i32

The goal here is to generate tokens for some unknown string of code.

let thing = "4";
let tokens = quote! { let thing = #thing }; // i32

or

let thing = ""4"";
let tokens = quote! { let thing = #thing }; // str
like image 518
garrettmaring Avatar asked Feb 20 '26 20:02

garrettmaring


1 Answers

how can one convert [a string] into a TokenStream

Rust has a common trait for converting strings into values when that conversion might fail: FromStr. This is usually accessed via the parse method on &str.

proc_macro2::TokenStream

use proc_macro2; // 0.4.24

fn example(s: &str) {
    let stream: proc_macro2::TokenStream = s.parse().unwrap();
}

proc_macro::TokenStream

extern crate proc_macro;

fn example(s: &str) {
    let stream: proc_macro::TokenStream = s.parse().unwrap();
}

You should be aware that this code cannot be run outside of the invocation of an actual procedural macro.

like image 152
Shepmaster Avatar answered Feb 24 '26 09:02

Shepmaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!