Automatically replace all try!() with `?`


#1

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.


Why does cargo fix replace try!() with r#try!() instead of?
Why does cargo fix replace try!() with r#try!() instead of?
#2

Very cool! :+1:


#3

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?


#4

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


#5

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


#6

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

16