Automatically replace all try!() with `?`

If you’ve got code that still uses the try!() macro, you can quickly and accurately upgrade it to the ? operator.

  1. Create rules.rs file with:

    fn rule1<T,E,X: From<E>>(r: Result<T,E>) -> Result<T,X> {
        replace!(try!(r) => r?);
        unreachable!()
    }
    
  2. Then run:

    cargo +nightly install rerast
    cargo +nightly rerast --rules_file=rules.rs --force
    

and poof! the macro will be gone. Rerast operates on the AST and fixes priorities of operations if necessary, so it’s much smarter and more correct than textual find’n’replace.

37 Likes

Very cool! :+1:

Very cool indeed, it just surprised me by being authored by Google. I always thought they had restrictions on which languages can be used by Googlers.

This tool, once extended with support for other syntactic forms (e.g. statements) and ‘find definition’ and ‘find usages’ functionality, could go a long way towards proper refactoring support couldn’t it?

Not for side-projects - this (as well as several others written by Google employees) is not an official Google product.

1 Like

https://github.com/google/xi-editor is another project written by a google employee in rust

2 Likes

The next step would be to write a GitHub bot for this :wink:

16

5 Likes

There is another way for those project used rustfmt suggested by Jonas:

Use rustfmt and enable the use_try_shorthand config option.

1 Like