How to print type annotations for a program?

#1

Flow has a handy tool called “flow suggest” which will print out the inferred types of the whole program. for example:

$ cat main.js && echo "-----------" && flow suggest main.js
pow = (a: number): number => Math.pow(a, 2);
mut = (a, b) => pow(a + b);

mut(12.3, 34.5);
-----------
pow = ((a: number): number => Math.pow(a, 2));
mut = ((a: any, b: any): any => pow(a + b));

mut(12.3, 34.5);

I feel certain that rust has an equivalent, but I don’t know what it is. How would I do the same thing in a rust program?

0 Likes

#2

I don’t know of any tool that does this. But you can annotate your binding with : () and the compiler will tell you what type it thinks it should be:

2 |     let a: () = vec![1u8];
  |                 ^^^^^^^^^ expected (), found struct `std::vec::Vec`
0 Likes

#3

IntelliJ has an option that shows the inferred types in the editor.

0 Likes

#4
  • To annotate a lifetime for yourself or other people reading your code, you can write a type annotation after a binding, even for an empty one! (e.g., let _: type_annotation_here = expression_here;).

    for ref x in &[42_i32, 27] {
        let _: &&i32 = x;
    }
    
  • To get the exact type of an expression, the most used trick is the one @jethrogb showed;

  • But if you really want to have all your code type annotated, I don’t know if such a tool currently exists (it definitely could), but you can try to see the generated HIR:

fn main ()
{
   let mut v = Vec::new();
   v.push(42_i32);
}
$ cargo +nightly rustc -- -Zunpretty=hir,typed
fn main() ({    
   let mut v =                
       ((<Vec>::new as                
            fn() -> std::vec::Vec<i32> {<std::vec::Vec<T>><i32>::new})()                
           as std::vec::Vec<i32>);                
   ((v as std::vec::Vec<i32>).push((42i32 as i32)) as ());                
} as ())

But this one sadly does not show, for instance, that the .push() call is taking an &mut Vec<i32>.

So, for a more verbose (but more accurate) output, there is the MIR, which is even available in the playground (top left menu):

$ cargo +nightly rustc -- -Zunpretty=mir-cfg | xdot -

3 Likes

#5

What a great, thorough answer @Yandros!

I don’t know if such a tool currently exists (it definitely could)

I’m not an active rust-type-person, so I can’t write it, but I think it would be a super handy debugging/teaching tool!

1 Like