Skip to content

Rollup of 8 pull requests #140356

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 22 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
12dd4a1
Stabilise c_str_module
clarfonthey Feb 22, 2025
6be84b1
Somehow these stability attributes were able to be omitted before?
clarfonthey Feb 22, 2025
781949d
Use char::is_whitespace directly in str::trim*
DaniPopes Mar 27, 2025
676e29b
fix docs for `Peekable::next_if{_eq}`
yotamofek Mar 28, 2025
3536324
Fix detection of `main` function if there are expressions around it
GuillaumeGomez Apr 23, 2025
81438c0
Add regression ui test for #140162 and for #139651
GuillaumeGomez Apr 23, 2025
3ededc1
Improve code
GuillaumeGomez Apr 25, 2025
3ef98a5
If there is a `;` alone, we consider that the doctest needs to be put…
GuillaumeGomez Apr 25, 2025
43d8d89
clarified bootstrap optimization agrs
Kivooeo Apr 26, 2025
86969db
session: Cleanup `CanonicalizedPath::new`
petrochenkov Apr 26, 2025
9112c86
Update example to use `CStr::to_string_lossy`
shepmaster Apr 25, 2025
8608a3f
lint-docs: Don't hard-code the valid editions
ehuss Apr 26, 2025
1f108fe
Update lint-docs to default to Rust 2024
ehuss Apr 26, 2025
aa69e3a
Fix bad handling of macros if there is already a `main` function
GuillaumeGomez Apr 26, 2025
2257a1c
Rollup merge of #137439 - clarfonthey:c-str-module, r=tgross35
tgross35 Apr 27, 2025
719b5ba
Rollup merge of #139031 - DaniPopes:str-trim-closure, r=tgross35
tgross35 Apr 27, 2025
cc2bc2a
Rollup merge of #139090 - yotamofek:pr/peekable-next-if-docs, r=tgross35
tgross35 Apr 27, 2025
dc57338
Rollup merge of #140220 - GuillaumeGomez:doctest-main-wrapping, r=fmease
tgross35 Apr 27, 2025
e37a3bb
Rollup merge of #140297 - shepmaster:cstr-lossy, r=joboet
tgross35 Apr 27, 2025
c7d9335
Rollup merge of #140330 - Kivooeo:new-fix-five, r=clubby789
tgross35 Apr 27, 2025
b31ae0e
Rollup merge of #140339 - petrochenkov:capanew, r=lqd
tgross35 Apr 27, 2025
c718a63
Rollup merge of #140348 - ehuss:lint-docs-edition, r=compiler-errors
tgross35 Apr 27, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bootstrap.example.toml
Original file line number Diff line number Diff line change
Expand Up @@ -500,7 +500,7 @@
# building without optimizations takes much longer than optimizing. Further, some platforms
# fail to build without this optimization (c.f. #65352).
# The valid options are:
# true - Enable optimizations.
# true - Enable optimizations (same as 3).
# false - Disable optimizations.
# 0 - Disable optimizations.
# 1 - Basic optimizations.
Expand Down
8 changes: 4 additions & 4 deletions compiler/rustc_interface/src/tests.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#![allow(rustc::bad_opt_access)]
use std::collections::{BTreeMap, BTreeSet};
use std::collections::BTreeMap;
use std::num::NonZero;
use std::path::{Path, PathBuf};
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;

use rustc_abi::Align;
Expand Down Expand Up @@ -89,8 +89,8 @@ where
S: Into<String>,
I: IntoIterator<Item = S>,
{
let locations: BTreeSet<CanonicalizedPath> =
locations.into_iter().map(|s| CanonicalizedPath::new(Path::new(&s.into()))).collect();
let locations =
locations.into_iter().map(|s| CanonicalizedPath::new(PathBuf::from(s.into()))).collect();

ExternEntry {
location: ExternLocation::ExactPaths(locations),
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_lint/src/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -948,7 +948,7 @@ declare_lint! {
///
/// ### Example
///
/// ```rust,compile_fail
/// ```rust,compile_fail,edition2021
/// #[no_mangle]
/// const FOO: i32 = 5;
/// ```
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_lint/src/impl_trait_overcaptures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ declare_lint! {
///
/// ### Example
///
/// ```rust,compile_fail
/// ```rust,compile_fail,edition2021
/// # #![deny(impl_trait_overcaptures)]
/// # use std::fmt::Display;
/// let mut x = vec![];
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_lint_defs/src/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1424,7 +1424,7 @@ declare_lint! {
///
/// ### Example
///
/// ```rust,compile_fail
/// ```rust,compile_fail,edition2021
/// macro_rules! foo {
/// () => {};
/// ($name) => { };
Expand Down Expand Up @@ -4128,7 +4128,7 @@ declare_lint! {
///
/// ### Example
///
/// ```rust,compile_fail
/// ```rust,compile_fail,edition2021
/// #![deny(dependency_on_unit_never_type_fallback)]
/// fn main() {
/// if true {
Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_session/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2323,14 +2323,13 @@ pub fn parse_externs(
let ExternOpt { crate_name: name, path, options } =
split_extern_opt(early_dcx, unstable_opts, &arg).unwrap_or_else(|e| e.emit());

let path = path.map(|p| CanonicalizedPath::new(p.as_path()));

let entry = externs.entry(name.to_owned());

use std::collections::btree_map::Entry;

let entry = if let Some(path) = path {
// --extern prelude_name=some_file.rlib
let path = CanonicalizedPath::new(path);
match entry {
Entry::Vacant(vacant) => {
let files = BTreeSet::from_iter(iter::once(path));
Expand Down
6 changes: 3 additions & 3 deletions compiler/rustc_session/src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::path::{Path, PathBuf};
use std::path::PathBuf;
use std::sync::OnceLock;

use rustc_data_structures::profiling::VerboseTimingGuard;
Expand Down Expand Up @@ -104,8 +104,8 @@ pub struct CanonicalizedPath {
}

impl CanonicalizedPath {
pub fn new(path: &Path) -> Self {
Self { original: path.to_owned(), canonicalized: try_canonicalize(path).ok() }
pub fn new(path: PathBuf) -> Self {
Self { canonicalized: try_canonicalize(&path).ok(), original: path }
}

pub fn canonicalized(&self) -> &PathBuf {
Expand Down
2 changes: 2 additions & 0 deletions library/alloc/src/ffi/c_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -818,6 +818,7 @@ impl From<Vec<NonZero<u8>>> for CString {
}
}

#[stable(feature = "c_string_from_str", since = "1.85.0")]
impl FromStr for CString {
type Err = NulError;

Expand All @@ -830,6 +831,7 @@ impl FromStr for CString {
}
}

#[stable(feature = "c_string_from_str", since = "1.85.0")]
impl TryFrom<CString> for String {
type Error = IntoStringError;

Expand Down
2 changes: 1 addition & 1 deletion library/alloc/src/ffi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,5 +87,5 @@ pub use self::c_str::CString;
#[stable(feature = "alloc_c_string", since = "1.64.0")]
pub use self::c_str::{FromVecWithNulError, IntoStringError, NulError};

#[unstable(feature = "c_str_module", issue = "112134")]
#[stable(feature = "c_str_module", since = "CURRENT_RUSTC_VERSION")]
pub mod c_str;
5 changes: 3 additions & 2 deletions library/core/src/ffi/c_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,9 @@ use crate::{fmt, ops, slice, str};
///
/// fn my_string_safe() -> String {
/// let cstr = unsafe { CStr::from_ptr(my_string()) };
/// // Get copy-on-write Cow<'_, str>, then guarantee a freshly-owned String allocation
/// String::from_utf8_lossy(cstr.to_bytes()).to_string()
/// // Get a copy-on-write Cow<'_, str>, then extract the
/// // allocated String (or allocate a fresh one if needed).
/// cstr.to_string_lossy().into_owned()
/// }
///
/// println!("string: {}", my_string_safe());
Expand Down
2 changes: 1 addition & 1 deletion library/core/src/ffi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub use self::c_str::FromBytesUntilNulError;
pub use self::c_str::FromBytesWithNulError;
use crate::fmt;

#[unstable(feature = "c_str_module", issue = "112134")]
#[stable(feature = "c_str_module", since = "CURRENT_RUSTC_VERSION")]
pub mod c_str;

#[unstable(
Expand Down
6 changes: 3 additions & 3 deletions library/core/src/iter/adapters/peekable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ impl<I: Iterator> Peekable<I> {
/// assert_eq!(iter.next_if(|&x| x == 0), Some(0));
/// // The next item returned is now 1, so `next_if` will return `None`.
/// assert_eq!(iter.next_if(|&x| x == 0), None);
/// // `next_if` saves the value of the next item if it was not equal to `expected`.
/// // `next_if` retains the next item if the predicate evaluates to `false` for it.
/// assert_eq!(iter.next(), Some(1));
/// ```
///
Expand Down Expand Up @@ -304,9 +304,9 @@ impl<I: Iterator> Peekable<I> {
/// let mut iter = (0..5).peekable();
/// // The first item of the iterator is 0; consume it.
/// assert_eq!(iter.next_if_eq(&0), Some(0));
/// // The next item returned is now 1, so `next_if` will return `None`.
/// // The next item returned is now 1, so `next_if_eq` will return `None`.
/// assert_eq!(iter.next_if_eq(&0), None);
/// // `next_if_eq` saves the value of the next item if it was not equal to `expected`.
/// // `next_if_eq` retains the next item if it was not equal to `expected`.
/// assert_eq!(iter.next(), Some(1));
/// ```
#[stable(feature = "peekable_next_if", since = "1.51.0")]
Expand Down
6 changes: 3 additions & 3 deletions library/core/src/str/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2115,7 +2115,7 @@ impl str {
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_diagnostic_item = "str_trim"]
pub fn trim(&self) -> &str {
self.trim_matches(|c: char| c.is_whitespace())
self.trim_matches(char::is_whitespace)
}

/// Returns a string slice with leading whitespace removed.
Expand Down Expand Up @@ -2154,7 +2154,7 @@ impl str {
#[stable(feature = "trim_direction", since = "1.30.0")]
#[rustc_diagnostic_item = "str_trim_start"]
pub fn trim_start(&self) -> &str {
self.trim_start_matches(|c: char| c.is_whitespace())
self.trim_start_matches(char::is_whitespace)
}

/// Returns a string slice with trailing whitespace removed.
Expand Down Expand Up @@ -2193,7 +2193,7 @@ impl str {
#[stable(feature = "trim_direction", since = "1.30.0")]
#[rustc_diagnostic_item = "str_trim_end"]
pub fn trim_end(&self) -> &str {
self.trim_end_matches(|c: char| c.is_whitespace())
self.trim_end_matches(char::is_whitespace)
}

/// Returns a string slice with leading whitespace removed.
Expand Down
2 changes: 1 addition & 1 deletion library/std/src/ffi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@
#![stable(feature = "rust1", since = "1.0.0")]

#[unstable(feature = "c_str_module", issue = "112134")]
#[stable(feature = "c_str_module", since = "CURRENT_RUSTC_VERSION")]
pub mod c_str;

#[stable(feature = "core_c_void", since = "1.30.0")]
Expand Down
1 change: 0 additions & 1 deletion library/std/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,6 @@
#![feature(array_chunks)]
#![feature(bstr)]
#![feature(bstr_internals)]
#![feature(c_str_module)]
#![feature(char_internals)]
#![feature(clone_to_uninit)]
#![feature(core_intrinsics)]
Expand Down
27 changes: 22 additions & 5 deletions src/librustdoc/doctest/make.rs
Original file line number Diff line number Diff line change
Expand Up @@ -407,17 +407,27 @@ fn parse_source(source: &str, crate_name: &Option<&str>) -> Result<ParseSourceIn
push_to_s(&mut info.crate_attrs, source, attr.span, &mut prev_span_hi);
}
}
let mut has_non_items = false;
for stmt in &body.stmts {
let mut is_extern_crate = false;
match stmt.kind {
StmtKind::Item(ref item) => {
is_extern_crate = check_item(&item, &mut info, crate_name);
}
StmtKind::Expr(ref expr) if matches!(expr.kind, ast::ExprKind::Err(_)) => {
reset_error_count(&psess);
return Err(());
StmtKind::Expr(ref expr) => {
if matches!(expr.kind, ast::ExprKind::Err(_)) {
reset_error_count(&psess);
return Err(());
}
has_non_items = true;
}
StmtKind::MacCall(ref mac_call) if !info.has_main_fn => {
// We assume that the macro calls will expand to item(s) even though they could
// expand to statements and expressions. And the simple fact that we're trying
// to retrieve a `main` function inside it is a terrible idea.
StmtKind::MacCall(ref mac_call) => {
if info.has_main_fn {
continue;
}
let mut iter = mac_call.mac.args.tokens.iter();

while let Some(token) = iter.next() {
Expand All @@ -437,7 +447,9 @@ fn parse_source(source: &str, crate_name: &Option<&str>) -> Result<ParseSourceIn
}
}
}
_ => {}
_ => {
has_non_items = true;
}
}

// Weirdly enough, the `Stmt` span doesn't include its attributes, so we need to
Expand All @@ -462,6 +474,11 @@ fn parse_source(source: &str, crate_name: &Option<&str>) -> Result<ParseSourceIn
push_to_s(&mut info.crates, source, span, &mut prev_span_hi);
}
}
if has_non_items {
// FIXME: if `info.has_main_fn` is `true`, emit a warning here to mention that
// this code will not be called.
info.has_main_fn = false;
}
Ok(info)
}
Err(e) => {
Expand Down
22 changes: 8 additions & 14 deletions src/tools/lint-docs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -444,21 +444,15 @@ impl<'a> LintExtractor<'a> {
fs::write(&tempfile, source)
.map_err(|e| format!("failed to write {}: {}", tempfile.display(), e))?;
let mut cmd = Command::new(self.rustc_path);
if options.contains(&"edition2024") {
cmd.arg("--edition=2024");
cmd.arg("-Zunstable-options");
} else if options.contains(&"edition2021") {
cmd.arg("--edition=2021");
} else if options.contains(&"edition2018") {
cmd.arg("--edition=2018");
} else if options.contains(&"edition2015") {
cmd.arg("--edition=2015");
} else if options.contains(&"edition") {
panic!("lint-docs: unknown edition");
} else {
let edition = options
.iter()
.filter_map(|opt| opt.strip_prefix("edition"))
.next()
// defaults to latest edition
cmd.arg("--edition=2021");
}
.unwrap_or("2024");
cmd.arg(format!("--edition={edition}"));
// Just in case this is an unstable edition.
cmd.arg("-Zunstable-options");
cmd.arg("--error-format=json");
cmd.arg("--target").arg(self.rustc_target);
if let Some(target_linker) = self.rustc_linker {
Expand Down
1 change: 1 addition & 0 deletions tests/rustdoc-ui/doctest/auxiliary/macro-after-main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
use std::string::String;
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@
//@ compile-flags:--test
//@ normalize-stdout: "tests/rustdoc-ui/doctest" -> "$$DIR"
//@ normalize-stdout: "finished in \d+\.\d+s" -> "finished in $$TIME"
//@ failure-status: 101
//@ check-pass

/// <https://github.com/rust-lang/rust/issues/91014>
///
/// ```rust
/// struct S {}; // unexpected semicolon after struct def
/// struct S {};
///
/// fn main() {
/// assert_eq!(0, 1);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,29 +1,6 @@

running 1 test
test $DIR/failed-doctest-extra-semicolon-on-item.rs - m (line 11) ... FAILED
test $DIR/failed-doctest-extra-semicolon-on-item.rs - m (line 11) ... ok

failures:

---- $DIR/failed-doctest-extra-semicolon-on-item.rs - m (line 11) stdout ----
error: expected item, found `;`
--> $DIR/failed-doctest-extra-semicolon-on-item.rs:12:12
|
LL | struct S {}; // unexpected semicolon after struct def
| ^
|
= help: braced struct declarations are not followed by a semicolon
help: remove this semicolon
|
LL - struct S {}; // unexpected semicolon after struct def
LL + struct S {} // unexpected semicolon after struct def
|

error: aborting due to 1 previous error

Couldn't compile the test.

failures:
$DIR/failed-doctest-extra-semicolon-on-item.rs - m (line 11)

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME

16 changes: 16 additions & 0 deletions tests/rustdoc-ui/doctest/macro-after-main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// This test checks a corner case where the macro calls used to be skipped,
// making them considered as statement, and therefore some cases where
// `include!` macro was then put into a function body, making the doctest
// compilation fail.

//@ compile-flags:--test
//@ normalize-stdout: "tests/rustdoc-ui/doctest" -> "$$DIR"
//@ normalize-stdout: "finished in \d+\.\d+s" -> "finished in $$TIME"
//@ check-pass

//! ```
//! include!("./auxiliary/macro-after-main.rs");
//!
//! fn main() {}
//! eprintln!();
//! ```
6 changes: 6 additions & 0 deletions tests/rustdoc-ui/doctest/macro-after-main.stdout
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@

running 1 test
test $DIR/macro-after-main.rs - (line 11) ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME

22 changes: 22 additions & 0 deletions tests/rustdoc-ui/doctest/test-main-alongside-exprs.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// This test ensures that if there is an expression alongside a `main`
// function, it will not consider the entire code to be part of the `main`
// function and will generate its own function to wrap everything.
//
// This is a regression test for:
// * <https://github.com/rust-lang/rust/issues/140162>
// * <https://github.com/rust-lang/rust/issues/139651>
//@ compile-flags:--test
//@ normalize-stdout: "tests/rustdoc-ui/doctest" -> "$$DIR"
//@ normalize-stdout: "finished in \d+\.\d+s" -> "finished in $$TIME"
//@ check-pass

#![crate_name = "foo"]

//! ```
//! # if cfg!(miri) { return; }
//! use std::ops::Deref;
//!
//! fn main() {
//! println!("Hi!");
//! }
//! ```
6 changes: 6 additions & 0 deletions tests/rustdoc-ui/doctest/test-main-alongside-exprs.stdout
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@

running 1 test
test $DIR/test-main-alongside-exprs.rs - (line 15) ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME

Loading