Skip to content

Syntax extension to generate unique identifiers #9031

Closed
@sfackler

Description

@sfackler

When writing a macro, it's common to use a couple of temporary variables, for example m in https://gist.github.com/luqmana/6219956. However, if you do something like

let m = 10;
let h = hashmap! {
    "foo" => m
};

The macro's internal m ends up being inserted, creating a type of infinite size. You can try to get around this issue by changing m to something like __hashmap_temp_var_, but you can still run into issues if, for example, you have nested invocations of a macro or if someone decides to be a jerk and define a variable called __hashmap_temp_var_.

It'd be nice to have a syntax extension that will generate identifiers that are guaranteed to be unique. I'd imagine it'd be used something like

macro_rules! my_macro (
    ($a:expr) => (
        {
            let unique_ident!(m) = HashMap::new();
            let unique_ident!(v) = ~[];
            unique_ident!(v).push($a);
            unique_ident!(m).insert("foo", $a);
            (unique_ident!(v), unique_ident!(m))
        }
    )
)

The implementation would be interesting, since you'd have to make sure that unique_ident!(m) expands to the same thing within a given macro expansion, but to a different thing within any nested expansions. You'd also want to make sure it doesn't shadow any other variables in scope, maybe by using a name that would be illegal to manually define.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions