1263 Commits

Author SHA1 Message Date
Matthias Krüger
4602127362 Rollup merge of #144444 - dawidl022:contracts/variable-scoping-rebased, r=jackh726
Contract variable declarations

This change adds contract variables that can be declared in the `requires` clause and can be referenced both in `requires` and `ensures`, subject to usual borrow checking rules. This allows any setup common to both the `requires` and `ensures` clauses to only be done once.

In particular, one future use case would be for [Fulminate](https://dl.acm.org/doi/10.1145/3704879)-like ownership assertions in contracts, that are essentially side-effects, and executing them twice would alter the semantics of the contract.

As of this change, `requires` can now be an arbitrary sequence of statements, with the final expression being of type `bool`. They are executed in sequence as expected, before checking if the final `bool` expression holds.

This PR depends on rust-lang/rust#144438 (which has now been merged).

Contracts tracking issue: https://github.com/rust-lang/rust/issues/128044

**Other changes introduced**:
- Contract macros now wrap the content in braces to produce blocks, meaning there's no need to wrap the content in `{}` when using multiple statements. The change is backwards compatible, in that wrapping the content in `{}` still works as before. The macros also now treat `requires` and `ensures` uniformally, meaning the `requires` closure is built inside the parser, as opposed to in the macro.

**Known limiatations**:
- Contracts with variable declarations are subject to the regular borrow checking rules, and the way contracts are currently lowered limits the usefulness of contract variable declarations. Consider the below example:

  ```rust
  #[requires(let init_x = *x; true)]
  #[ensures(move |_| *x == 2 * init_x)]
  fn double_in_place(x: &mut i32) {
      *x *= 2;
  }
  ```

  We have used the new variable declarations feature to remember the initial value pointed to by `x`, however, moving `x` into the `ensures` does not pass the borrow checker, meaning the above function contract is illegal. Ideally, something like the above should be expressable in contracts.
2025-10-29 08:07:49 +01:00
Camille Gillot
15c91bf308 Retire ast::TyAliasWhereClauses. 2025-10-23 00:40:01 +00:00
bors
4d94478977 Auto merge of #147826 - Muscraft:update-typos, r=Noratrieb
Update typos

I saw that `typos` was a few versions out of date and figured it would be a good idea to update it. Upgrading to `1.38.1` adds the [July](https://github.com/crate-ci/typos/issues/1331), [August](https://github.com/crate-ci/typos/issues/1345), and [September](https://github.com/crate-ci/typos/issues/1370) dictionary updates. As part of this change, I also sorted the configuration file.
2025-10-22 13:11:47 +00:00
Oli Scherer
ad4bd083f3 Add not-null pointer patterns to pattern types 2025-10-21 11:22:51 +00:00
Scott Schafer
12f6b9697f chore: Update typos to 1.38.1 2025-10-20 12:20:15 -06:00
Dawid Lachowicz
aeae085dc3 Add contract variable declarations
Contract variables can be declared in the `requires` clause and
can be referenced both in `requires` and `ensures`, subject to usual
borrow checking rules.

This allows any setup common to both the `requires` and `ensures`
clauses to only be done once.
2025-10-18 15:00:34 +01:00
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
bors
f5242367f4 Auto merge of #146221 - camsteffen:ast-boxes, r=cjgillot
Remove boxes from ast list elements

Less indirection should be better perf.
2025-10-16 02:31:44 +00:00
Matthias Krüger
6908bca90f Rollup merge of #147710 - chenyukang:yukang-fix-ice-contracts-async, r=jackh726
Fix ICE when using contracts on async functions

Fixes rust-lang/rust#145333

contract is not supported for async functions right now, it's not properly lowered and getting HirId will ICE.

This PR adds checking for async function in expanding AST phase, it's better until we want to fully support async for contracts feature.
2025-10-15 23:41:04 +02:00
yukang
0935df7829 Fix ICE when using contracts on async functions 2025-10-15 09:09:23 +08:00
Matthias Krüger
ea0c8d8e73 Rollup merge of #147682 - jdonszelmann:convert-rustc-main, r=JonathanBrouwer
convert `rustc_main` to the new attribute parsing infrastructure

r? ``@JonathanBrouwer``
2025-10-14 19:47:34 +02:00
Jana Dönszelmann
047c37cf23 convert rustc_main to the new attribute parsing infrastructure 2025-10-14 17:55:00 +02:00
Dawid Lachowicz
a172a66ae8 Wrap contract clauses in brances instead of parenthesis
The compiler complained about uncecessary parenthesis on contract clauses,
which were insterted by the contract macros. This commit changes the
macro to use braces as the delimiter instead, fixing the issue.
2025-10-11 00:16:44 +01:00
bjorn3
7e467cd132 Move computation of allocator shim contents to cg_ssa
In the future this should make it easier to use weak symbols for the
allocator shim on platforms that properly support weak symbols. And it
would allow reusing the allocator shim code for handling default
implementations of the upcoming externally implementable items feature
on platforms that don't properly support weak symbols.
2025-10-10 13:04:55 +00:00
bjorn3
116f4ae171 Support #[alloc_error_handler] without the allocator shim
Currently it is possible to avoid linking the allocator shim when
__rust_no_alloc_shim_is_unstable_v2 is defined when linking rlibs
directly as some build systems need. However this requires liballoc to
be compiled with --cfg no_global_oom_handling, which places huge
restrictions on what functions you can call and makes it impossible to
use libstd. Or alternatively you have to define
__rust_alloc_error_handler and (when using libstd)
__rust_alloc_error_handler_should_panic
using #[rustc_std_internal_symbol]. With this commit you can either use
libstd and define __rust_alloc_error_handler_should_panic or not use
libstd and use #[alloc_error_handler] instead. Both options are still
unstable though.

Eventually the alloc_error_handler may either be removed entirely
(though the PR for that has been stale for years now) or we may start
using weak symbols for it instead. For the latter case this commit is a
prerequisite anyway.
2025-10-10 13:04:53 +00:00
Stuart Cook
9ace0de26b Rollup merge of #147489 - chenyukang:yukang-prefer-repeat-n, r=Kivooeo,oli-obk
Prefer to use repeat_n over repeat().take()

More from https://github.com/rust-lang/rust/pull/147464, but batch processed with `ast-grep` to find and replace.

second commit add notes for library: affaf532f9

r? ``@RalfJung``
2025-10-09 18:43:26 +11:00
yukang
1654cce210 prefer to use repeat_n over repeat and take 2025-10-09 01:24:55 +08:00
Marijn Schouten
d4ecd710a5 format: some small cleanup 2025-10-08 15:13:47 +00:00
Kivooeo
67bc030833 change flt back to ftl 2025-10-04 18:18:58 +00:00
Cameron Steffen
703584604a Remove boxes from ast TyPat lists 2025-10-04 12:39:58 -05:00
Cameron Steffen
c44500b4a1 Remove boxes from ast Pat lists 2025-10-04 12:39:58 -05:00
Yotam Ofek
68a7c25078 Use Iterator::eq and (dogfood) eq_by in compiler and library 2025-09-29 08:08:05 +03:00
Stuart Cook
46e25aa7a3 Rollup merge of #146766 - nikic:global-alloc-attr, r=nnethercote
Add attributes for #[global_allocator] functions

Emit `#[rustc_allocator]` etc. attributes on the functions generated by the `#[global_allocator]` macro, which will emit LLVM attributes like `"alloc-family"`. If the module with the global allocator participates in LTO, this ensures that the attributes typically emitted on the allocator declarations are not lost if the definition is imported.

There is a similar issue when the allocator shim is used, but I've opted not to fix that case in this PR, because doing that cleanly is somewhat gnarly.

Related to https://github.com/rust-lang/rust/issues/145995.
2025-09-25 20:31:56 +10:00
Nikita Popov
bc7986ec79 Add attributes for #[global_allocator] functions
Emit `#[rustc_allocator]` etc. attributes on the functions generated
by the `#[global_allocator]` macro, which will emit LLVM attributes
like `"alloc-family"`. If the module with the global allocator
participates in LTO, this ensures that the attributes typically
emitted on the allocator declarations are not lost if the
definition is imported.
2025-09-23 10:21:17 +02:00
Ben Kimock
888679013d Add panic=immediate-abort 2025-09-21 13:12:18 -04:00
Jana Dönszelmann
9303a924f4 Rollup merge of #146598 - bjorn3:feature_llvm_enzyme, r=davidtwco
Make llvm_enzyme a regular cargo feature

This makes it clearer that it is set by the build system rather than by the rustc that compiles the current rustc. It also avoids bootstrap needing to pass `--check-cfg llvm_enzyme` to rustc.
2025-09-17 20:29:36 +02:00
Stuart Cook
edd6721583 Rollup merge of #145095 - tiif:unstable_const_param, r=BoxyUwU
Migrate `UnsizedConstParamTy`  to unstable impl of `ConstParamTy_`

Now that we have ``#[unstable_feature_bound]``, we can remove ``UnsizedConstParamTy`` that was meant to be an unstable impl of stable type and ``ConstParamTy_`` trait.

r? `@BoxyUwU`
2025-09-16 10:25:38 +10:00
bjorn3
1991779bd4 Make llvm_enzyme a regular cargo feature
This makes it clearer that it is set by the build system rather than by
the rustc that compiles the current rustc. It also avoids bootstrap
needing to pass --check-cfg llvm_enzyme to rustc.
2025-09-15 15:31:56 +00:00
tiif
b919a5f518 Remove UnsizedConstParamTy trait and make it into an unstable impl 2025-09-15 08:57:22 +00:00
León Orell Valerian Liehr
2e816736ef Move more early buffered lints to dyn lint diagnostics (1/N) 2025-09-14 12:38:11 +02:00
IoaNNUwU
43a6b10418 Use raw fmt str in format macro 2025-09-12 00:01:38 +02:00
Jieyou Xu
b38a86f4d7 Revert "Rollup merge of #122661 - estebank:assert-macro-span, r=petrochenkov"
This reverts commit 1eeb8e8b15, reversing
changes made to 324bf2b9fd.

Unfortunately the assert desugaring change is not backwards compatible,
see RUST-145770.

Code such as

```rust
#[derive(Debug)]
struct F {
    data: bool
}

impl std::ops::Not for F {
  type Output = bool;
  fn not(self) -> Self::Output { !self.data }
}

fn main() {
  let f = F { data: true };

  assert!(f);
}
```

would be broken by the assert desugaring change. We may need to land
the change over an edition boundary, or limit the editions that the
desugaring change impacts.
2025-09-11 09:10:46 +08:00
Matthias Krüger
86d39a0673 Rollup merge of #146340 - fmease:frontmatter-containment, r=fee1-dead,Urgau
Strip frontmatter in fewer places

* Stop stripping frontmatter in `proc_macro::Literal::from_str` (RUST-146132)
* Stop stripping frontmatter in expr-ctxt (but not item-ctxt!) `include`s (RUST-145945)
* Stop stripping shebang (!) in `proc_macro::Literal::from_str`
  * Not a breaking change because it did compare spans already to ensure there wasn't extra whitespace or comments (`Literal::from_str("#!\n0")` already yields `Err(_)` thankfully!)
* Stop stripping frontmatter+shebang inside some rustdoc code where it doesn't make any observable difference (see self review comments)
* (Stop stripping frontmatter+shebang inside internal test code)

Fixes https://github.com/rust-lang/rust/issues/145945.
Fixes https://github.com/rust-lang/rust/issues/146132.

r? fee1-dead
2025-09-10 20:29:09 +02:00
León Orell Valerian Liehr
7a66925a81 Strip frontmatter in fewer places 2025-09-09 19:49:40 +02:00
León Orell Valerian Liehr
ec87250101 Improve docs of certain built-in macro expanders 2025-09-09 17:16:50 +02:00
IoaNNUwU
43a6f56ca7 Apply requested changes 2025-09-08 19:19:59 +02:00
IoaNNUwU
1e733b3891 Implement better suggestions based on additional tests and other code paths 2025-09-08 17:35:40 +02:00
IoaNNUwU
e656e52ccb Suggest examples of format specifiers in error messages 2025-09-08 17:35:40 +02:00
Nicholas Nethercote
301655eafe Revert introduction of [workspace.dependencies].
This was done in #145740 and #145947. It is causing problems for people
using r-a on anything that uses the rustc-dev rustup package, e.g. Miri,
clippy.

This repository has lots of submodules and subtrees and various
different projects are carved out of pieces of it. It seems like
`[workspace.dependencies]` will just be more trouble than it's worth.
2025-09-02 19:12:54 +10:00
Matthias Krüger
bd90013b39 Rollup merge of #145905 - TaKO8Ki:fix-137580, r=nnethercote
Stop calling unwrap when format foreign has trailing dollar

Fixes rust-lang/rust#137580
2025-08-27 11:26:52 +02:00
Nicholas Nethercote
c50d2cc807 Add tracing to [workspace.dependencies]. 2025-08-27 14:21:19 +10:00
Nicholas Nethercote
777e2d6a2a Add thin-vec to newly added [workspace.dependencies]. 2025-08-27 13:59:32 +10:00
Takayuki Maeda
adddae6536 stop returning errors when format foreign has trailing dollar 2025-08-27 06:06:11 +09:00
Jacob Pratt
d3c9908a8a Rollup merge of #145747 - joshtriplett:builtin-diag-dyn, r=jdonszelmann
Refactor lint buffering to avoid requiring a giant enum

Lint buffering currently relies on a giant enum `BuiltinLintDiag` containing all the lints that might potentially get buffered. In addition to being an unwieldy enum in a central crate, this also makes `rustc_lint_defs` a build bottleneck: it depends on various types from various crates (with a steady pressure to add more), and many crates depend on it.

Having all of these variants in a separate crate also prevents detecting when a variant becomes unused, which we can do with a dedicated type defined and used in the same crate.

Refactor this to use a dyn trait, to allow using `LintDiagnostic` types directly.

Because the existing `BuiltinLintDiag` requires some additional types in order to decorate some variants, which are only available later in `rustc_lint`, use an enum `DecorateDiagCompat` to handle both the `dyn LintDiagnostic` case and the `BuiltinLintDiag` case.

---

With the infrastructure in place, use it to migrate three of the enum variants to use `LintDiagnostic` directly, as a proof of concept and to demonstrate that the net result is a reduction in code size and a removal of a boilerplate-heavy layer of indirection.

Also remove an unused `BuiltinLintDiag` variant.
2025-08-22 22:00:59 -04:00
Josh Triplett
c99320156d Refactor lint buffering to avoid requiring a giant enum
Lint buffering currently relies on a giant enum `BuiltinLintDiag`
containing all the lints that might potentially get buffered. In
addition to being an unwieldy enum in a central crate, this also makes
`rustc_lint_defs` a build bottleneck: it depends on various types from
various crates (with a steady pressure to add more), and many crates
depend on it.

Having all of these variants in a separate crate also prevents detecting
when a variant becomes unused, which we can do with a dedicated type
defined and used in the same crate.

Refactor this to use a dyn trait, to allow using `LintDiagnostic` types
directly.

This requires boxing, but all of this is already on the slow path
(emitting an error).

Because the existing `BuiltinLintDiag` requires some additional types in
order to decorate some variants, which are only available later in
`rustc_lint`, use an enum `DecorateDiagCompat` to handle both the `dyn
LintDiagnostic` case and the `BuiltinLintDiag` case.
2025-08-22 01:59:56 -07:00
Jonathan Brouwer
21d3189779 Move validate_attr to rustc_attr_parsing 2025-08-22 08:37:19 +02:00
Jacob Pratt
25b81bf5ad Rollup merge of #145590 - nnethercote:ModKind-Inline, r=petrochenkov
Prevent impossible combinations in `ast::ModKind`.

`ModKind::Loaded` has an `inline` field and a `had_parse_error` field. If the `inline` field is `Inline::Yes` then `had_parse_error` must be `Ok(())`.

This commit moves the `had_parse_error` field into the `Inline::No` variant. This makes it impossible to create the nonsensical combination of `inline == Inline::Yes` and `had_parse_error = Err(_)`.

r? ```@Urgau```
2025-08-21 01:12:19 -04:00
bors
f605b57042 Auto merge of #145601 - jieyouxu:rollup-t5mbqhc, r=jieyouxu
Rollup of 10 pull requests

Successful merges:

 - rust-lang/rust#145538 (bufreader::Buffer::backshift: don't move the uninit bytes)
 - rust-lang/rust#145542 (triagebot: Don't warn no-mentions on subtree updates)
 - rust-lang/rust#145549 (Update rust maintainers in openharmony.md)
 - rust-lang/rust#145550 (Avoid using `()` in `derive(From)` output.)
 - rust-lang/rust#145556 (Allow stability attributes on extern crates)
 - rust-lang/rust#145560 (Remove unused `PartialOrd`/`Ord` from bootstrap)
 - rust-lang/rust#145568 (ignore frontmatters in `TokenStream::new`)
 - rust-lang/rust#145571 (remove myself from some adhoc-groups and pings)
 - rust-lang/rust#145576 (Add change tracker entry for `--timings`)
 - rust-lang/rust#145578 (Add VEXos "linked files" support to `armv7a-vex-v5`)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-08-19 23:52:06 +00:00
Nicholas Nethercote
bfd5d59f97 Prevent impossible combinations in ast::ModKind.
`ModKind::Loaded` has an `inline` field and a `had_parse_error` field.
If the `inline` field is `Inline::Yes` then `had_parse_error` must be
`Ok(())`.

This commit moves the `had_parse_error` field into the `Inline::No`
variant. This makes it impossible to create the nonsensical combination
of `inline == Inline::Yes` and `had_parse_error = Err(_)`.
2025-08-19 21:57:31 +10:00
许杰友 Jieyou Xu (Joe)
62227334ae Rollup merge of #145429 - bjorn3:codegen_fn_attrs_improvements, r=jdonszelmann
Couple of codegen_fn_attrs improvements

As noted in https://github.com/rust-lang/rust/pull/144678#discussion_r2245060329 here is no need to keep link_name and export_name separate, which the third commit fixes by merging them. The second commit removes some dead code and the first commit merges two ifs with equivalent conditions. The last commit is an unrelated change which removes an unused `feature(autodiff)`.
2025-08-19 19:45:31 +08:00