Where Is Type Checking?

Documents regarding the type checking is too ambiguous, both is Rust Compiler Book and the Docs in the Rustc source.

My question is, in a simple word, where is type checking happens in the Rustc? Some part of the doc says it is at the HIR level. We see typeck appear in almost every part of the Rustc, such as: rustc_hir_analysis, rustc_hir_typeck, rustc_borrowck, rustc_type_ir, etc.

To be precise, I want to know the flow of type checking/inference in Rustc. Either it is at the HIR, or MIR, hir::Ty or ty::Ty, etc. Where should I look for type comparison of "Ty A == Ty B" holds true or not?

Typechecking is done twice: First HIR typeck which also does type inference. This operates on ty::Ty. The second is MIR typeck which is used by MIR borrowck to collect all lifetime constraints implied by types. rustc_type_ir defines ty::Ty. rustc_hir_typeck is where HIR typeck is located I believe. The reference in rustc_hir_analysis is likely caused by rustc_hir_typeck getting split out of rustc_hir_analysis, but the docs not being updated. hir::Ty is a syntactical representation of types that gets lowered to ty::Ty.

3 Likes

Thanks for the explanation. I appreciate it. The docs and/or doc comments need to be updated btw!

Why is typechecking done twice? Isn't this too slow?

I thought it was done once in HIR, and then MIR had to deal just with borrowck

It's a necessary part of the borrow checker.

If you have a type struct Foo<'a, 'b: 'a>(&'a u8, &'b u8);, then if a function uses Foo, borrowck needs to know that there is a bound 'b: 'a that needs to be upheld. The way borrowck learns that this bound exists at all is by doing MIR typeck.