CodeBlanks Logo Icon CodeBlanks

Summary - Compiler internals

Combine HIR, MIR and LLVM IR to draw a compilation pipeline.

Compiler internals summary

The compilation pipeline: tokens → AST (macros, name resolution) → HIR (sugar removed, type checking, trait resolution) → MIR (control-flow graph, borrow checking, NLL, constant evaluation) → LLVM IR (optimization) → machine code. Type inference works by constraint unification within a function. Debug and release builds apply different checks and optimizations; for example, integer overflow checking is on by default only in debug.

Overflow with explicit intent

Integer methods make what happens on overflow the same in every build:

let x: u8 = 255;
println!("{:?}", x.checked_add(1));      // None
println!("{}", x.wrapping_add(1));       // 0
println!("{}", x.saturating_add(1));     // 255
println!("{:?}", x.overflowing_add(1));  // (0, true)

wrapping_* is the natural choice for counters and hashes, saturating_* for bounded values, checked_* for validation.

Practice Overflow methods

For let x: u8 = 255;, print the results of checked_add(1) ({:?}), wrapping_add(1) and saturating_add(1) on one line separated by spaces.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn main() {
    let x: u8 = 255;
    println!("{:?} {} {}", x.checked_add(1), x.wrapping_add(1), x.saturating_add(1));
}

Expected output

None 0 255

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens to <code>255u8 + 1</code> in a release build (with default settings)?

  • Always panics
  • It becomes 256
  • Always a compile error
  • It wraps to 0; in debug it panics Correct answer

Explanation: To keep behaviour independent of the build, state the intent explicitly: checked_add, wrapping_add, saturating_add. (The compiler already catches a constant expression as an error.)

2 Stay at the limit

Question
let x: u8 = 255;
let y = x.____(1);   // 255
Answer
let x: u8 = 255;
let y = x.saturating_add(1);   // 255

Explanation: saturating_add stays at the type's limit on overflow.

3 Method and 255u8 + 1 result

Term Meaning
checked_add None
wrapping_add 0
saturating_add 255
overflowing_add (0, true)

All lessons in Expert