Files
rust/compiler/rustc_mir_transform
Matthias Krüger 334b3af42c Rollup merge of #144438 - dawidl022:contracts/guarded-lowering, r=oli-obk
Guard HIR lowered contracts with `contract_checks`

Refactor contract HIR lowering to ensure no contract code is executed when contract-checks are disabled.

The call to `contract_checks` is moved to inside the lowered fn body, and contract closures are built conditionally, ensuring no side-effects present in contracts occur when those are disabled. This partially addresses rust-lang/rust#139548, i.e. the bad behavior no longer happens with contract checks disabled (`-Zcontract-checks=no`).

The change is made in preparation for adding contract variable declarations - variables declared before the `requires` assertion, and accessible from both `requires` and `ensures`, but not in the function body (PR rust-lang/rust#144444). As those declarations may also have side-effects, it's good to guard them with `contract_checks` - the new lowering approach allows for this to be done easily.

Contracts tracking issue: rust-lang/rust#128044

**Known limiatations**:

- It is still possible to early return from the *function* from within a contract, e.g.

  ```rust
  #[ensures({if x > 0 { return 0 }; |_| true})]
  fn foo(x: u32) -> i32 {
      42
  }
  ```

  When `foo` is called with an argument greater than 0, instead of `42`, `0` will be returned.

  As this is not a regression, it is not addressed in this PR. However, it may be worth revisiting later down the line, as users may expect a form of early return from *contract specifications*, and so returning from the entire *function* could cause confusion.

- ~Contracts are still not optimised out when disabled. Currently, even when contracts are disabled, the code generated causes existing optimisations to fail, meaning even disabled contracts could impact runtime performance. This issue is blocking rust-lang/rust#136578, and has not been addressed in this PR, i.e. the `mir-opt` and `codegen` tests that fail in rust-lang/rust#136578 still fail with these new HIR lowering changes.~ Contracts should now be optimised out when disabled, however some regressions tests still need to be added to be sure that is indeed the case.
2025-10-16 19:35:22 +02:00
..
2025-09-13 17:14:04 +00:00