rust-analyzer icon indicating copy to clipboard operation
rust-analyzer copied to clipboard

‘Extract into constant’ assist

Open lunacookies opened this issue 4 years ago • 8 comments

rust-analyzer currently has ‘Extract into variable’ and ‘Extract into function’ assists; I sometimes find myself using ‘Extract into variable’, renaming it to use a SCREAMING_SNAKE_CASE name, and adjusting the definition to use const. It would be nice to have an assist that does all this. Bonus: put the constant at the top of the file, after any use statements.

lunacookies avatar Feb 16 '21 07:02 lunacookies

Bonus: put the constant at the top of the file, after any use statements.

Since local const items are sometimes used, maybe it should extract to a local const item by default. Another new assist could handle the bonus behavior, i.e. "extract local item to top-level", that could be applied to any local items (local structs, functions, uses, etc).

memoryruins avatar Feb 16 '21 09:02 memoryruins

I'd find this useful as well. One more bonus thing that would be nice is RA looking for other instances of the same literal (or even const-evaluatable expression) in the same context and replacing those with the newly-defined const too.

jplatte avatar Jul 28 '21 14:07 jplatte

looking for other instances of the same literal

Hm, I would find false positives really unfortunate then :\

missile_guidance.hours_before_launch(1);
missile_guidance.set_number_of_targets(1);

The same literal is used above in the same context, but I doubt anyone is willing to extract them into the same const, right?

iago-lito avatar Jul 29 '21 07:07 iago-lito

Right, there might be cases where that's not desirable. In my case yesterday it was a string literal of >10 characters. Maybe there would have to be some heuristics?

jplatte avatar Jul 29 '21 08:07 jplatte

Lifted jonas comment out into its own issue https://github.com/rust-analyzer/rust-analyzer/issues/10547

Veykril avatar Oct 14 '21 20:10 Veykril

Given https://github.com/rust-analyzer/rust-analyzer/issues/10547#issuecomment-943710680, should this be re-opened?

jplatte avatar Oct 15 '21 12:10 jplatte

I suppose so ye

Veykril avatar Oct 15 '21 13:10 Veykril

For what it's worth for anyone else finding this, easiest workaround for me was to use the Generate Constant assist, so you select and cut the string literal, type the new name, then Generate Constant and paste the literal.

And https://github.com/rust-analyzer/rust-analyzer/pull/10546 seems like a good place to get inspiration for anyone looking to implement this.

gibfahn avatar Feb 14 '22 18:02 gibfahn

@rustbot claim

Giga-Bowser avatar Dec 08 '24 21:12 Giga-Bowser