Syn: parsing "let mut" and quote! directly without modification

Hello,

I'm trying to parse with syn

let mut t=0;
let l:u8=1;

First of all, I can't find any Expr... to parse the expression: it would be great to have a big file grouping all parsing features and usage. My goal is to replace let mut t=0; by let t=0;.

Finally, if I find a let, I need to push it as it was before parsing: I don't want to rewrite it in quote! by hand, but submit using something likeitem.unchanged() .

Is it possible ?

Thank you in advance for your help.

I think it's Expr::Let

and the mut t part should be parsed into ExprLet::pat:

specifically, it should be Pat::Ident

and the mut token corresponds to PatIdent::mutability

2 Likes

Just a general remark here. When parsing, it is often a good idea to parse complete expressions. Especially when you are concerned with valid Rust syntax and not your own user-defined one. Let's make an example:

Say I have a struct definition which I would like to parse.

struct HappyMe {
    happy_score: u8,
}

We could parse this by specifying all individual entries and parsing them:

struct StructParser {
    struct_token: syn::Token![struct],
    ident: syn::Ident,
    curly_brace:_left syn::Token![{],
    // ... and all the fields.
    curly_brace_right: syn::Token![}],
}

impl syn::parse::Parse for structParser {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        Ok(Self {
            struct_token: input.parse()?,
            ident: input.parse()?,
            curly_brace_left: input.parse()?,
            // .. and all the fields
            curly_brace_right: input.parse()?,
    }
}

However, what if we introduce other modifiers such as pub for fields etc.

struct HappyMe {
    pub happy_score: u8,
}

Now our parsing routine will not work anymore.
This is why I would recommend to parse the desired line of valid Rust code by the already predefined ways.

Thus I would recommend, using syn::ItemStatic as explained here: syn::token - Rust.
Once you have parsed the item, you can modify the relevant entries and return the modified version. This allows for greater portability and is imho the best way to do it.