How to add tabs and spaces to a python code generated via rust?

Wonderful community members, I have been playing with rust macros for a week now and came with a macro that generates (or at least tries to..) python code when I expand the macro i.e in the [EXPANSION].rs file.

Here is the macro what I came up with so far

macro_rules! genpy {
    (
        $(
            $Name: ident {
                $($Field: ident),* $(,)?
            }
        )*
    ) => {
        $(
            class $Name():
                def __init__(self, $($Field,)*):
                    $(
                        self.$Field = $Field
                    )*
        )*
    };
}

Then I call the macro in my main function like the following:

genpy!(Human { name, age sex })

If I open the [EXPANSION].rs in vscode, I see something like this.

// Recursive expansion of genpy! macro
// ===============================================

class Human():def __init__(self, name, age, sex,):self.name = name self.age = age self.sex = sex

Is there a way, I can make it look like

class Human():
    def __init__(self, name, age, sex):
        self.name = name
        self.age = age
        self.sex = sex

PS: I am not trying to run this code using rust, but, trying to generate a piece of code that looks like Python with indents and space.

Thanks a lot again for being an awesome community :slight_smile:

macro_rules! is purely designed to generate rust code, and I don't think there is even a mechanism to output to a file, which you'd need in order to use this. If your goal is to have users of macro write rust code that also generates some corresponding Python code, I'd suggest using proc macros. But the Python code itself wouldn't be the output of the proc macro (which is still required to be valid rust code) but rather a file you could create as a side effect.

1 Like

Ohkay, thank you for that direction. I will start looking at how I could get this going using procedural macros.

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.