Skip to content

Commit ae1c8ea

Browse files
borscompiler-errors
authored andcommitted
Auto merge of rust-lang#131859 - chriskrycho:update-trpl, r=onur-ozkan
Update TRPL to add new Chapter 17: Async and Await - Add support to `rustbook` to pass through the `-L`/`--library-path` flag to `mdbook` so that references to the `trpl` crate - Build the `trpl` crate as part of the book tests. Make it straightforward to add other such book dependencies in the future if needed by implementing that in a fairly general way. - Update the submodule for the book to pull in the new chapter on async and await, as well as a number of other fixes. This will happen organically/automatically in a week, too, but this lets me group this change with the next one: - Update the compiler messages which reference the existing chapters 17–20, which are now chapters 18-21. There are only two, both previously referencing chapter 18. - Update the UI tests which reference the compiler message outputs.
2 parents 15b663e + 7630b49 commit ae1c8ea

File tree

82 files changed

+297
-219
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

82 files changed

+297
-219
lines changed

compiler/rustc_hir_typeck/src/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -364,7 +364,7 @@ fn report_unexpected_variant_res(
364364
.with_code(err_code);
365365
match res {
366366
Res::Def(DefKind::Fn | DefKind::AssocFn, _) if err_code == E0164 => {
367-
let patterns_url = "https://doc.rust-lang.org/book/ch18-00-patterns.html";
367+
let patterns_url = "https://doc.rust-lang.org/book/ch19-00-patterns.html";
368368
err.with_span_label(span, "`fn` calls are not allowed in patterns")
369369
.with_help(format!("for more information, visit {patterns_url}"))
370370
}

compiler/rustc_middle/src/ty/consts.rs

-4
Original file line numberDiff line numberDiff line change
@@ -151,10 +151,6 @@ impl<'tcx> Const<'tcx> {
151151
}
152152

153153
impl<'tcx> rustc_type_ir::inherent::Const<TyCtxt<'tcx>> for Const<'tcx> {
154-
fn try_to_target_usize(self, interner: TyCtxt<'tcx>) -> Option<u64> {
155-
self.try_to_target_usize(interner)
156-
}
157-
158154
fn new_infer(tcx: TyCtxt<'tcx>, infer: ty::InferConst) -> Self {
159155
Const::new_infer(tcx, infer)
160156
}

compiler/rustc_middle/src/ty/error.rs

+3-6
Original file line numberDiff line numberDiff line change
@@ -58,12 +58,9 @@ impl<'tcx> TypeError<'tcx> {
5858
pluralize!(values.found)
5959
)
6060
.into(),
61-
TypeError::FixedArraySize(values) => format!(
62-
"expected an array with a fixed size of {} element{}, found one with {} element{}",
63-
values.expected,
64-
pluralize!(values.expected),
65-
values.found,
66-
pluralize!(values.found)
61+
TypeError::ArraySize(values) => format!(
62+
"expected an array with a size of {}, found one with a size of {}",
63+
values.expected, values.found,
6764
)
6865
.into(),
6966
TypeError::ArgCount => "incorrect number of function parameters".into(),

compiler/rustc_mir_build/messages.ftl

+1-1
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,7 @@ mir_build_lower_range_bound_must_be_less_than_or_equal_to_upper =
213213
214214
mir_build_lower_range_bound_must_be_less_than_upper = lower range bound must be less than upper
215215
216-
mir_build_more_information = for more information, visit https://doc.rust-lang.org/book/ch18-02-refutability.html
216+
mir_build_more_information = for more information, visit https://doc.rust-lang.org/book/ch19-02-refutability.html
217217
218218
mir_build_moved = value is moved into `{$name}` here
219219

compiler/rustc_parse/messages.ftl

+1-1
Original file line numberDiff line numberDiff line change
@@ -827,7 +827,7 @@ parse_unexpected_expr_in_pat =
827827
}, found an expression
828828
829829
.label = not a pattern
830-
.note = arbitrary expressions are not allowed in patterns: <https://doc.rust-lang.org/book/ch18-00-patterns.html>
830+
.note = arbitrary expressions are not allowed in patterns: <https://doc.rust-lang.org/book/ch19-00-patterns.html>
831831
832832
parse_unexpected_expr_in_pat_const_sugg = consider extracting the expression into a `const`
833833

compiler/rustc_resolve/src/late/diagnostics.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1206,7 +1206,7 @@ impl<'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
12061206
let PathSource::TupleStruct(_, _) = source else { return };
12071207
let Some(Res::Def(DefKind::Fn, _)) = res else { return };
12081208
err.primary_message("expected a pattern, found a function call");
1209-
err.note("function calls are not allowed in patterns: <https://doc.rust-lang.org/book/ch18-00-patterns.html>");
1209+
err.note("function calls are not allowed in patterns: <https://doc.rust-lang.org/book/ch19-00-patterns.html>");
12101210
}
12111211

12121212
fn suggest_changing_type_to_const_param(

compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs

+9-4
Original file line numberDiff line numberDiff line change
@@ -1792,12 +1792,12 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
17921792

17931793
fn suggest_specify_actual_length(
17941794
&self,
1795-
terr: TypeError<'_>,
1796-
trace: &TypeTrace<'_>,
1795+
terr: TypeError<'tcx>,
1796+
trace: &TypeTrace<'tcx>,
17971797
span: Span,
17981798
) -> Option<TypeErrorAdditionalDiags> {
17991799
let hir = self.tcx.hir();
1800-
let TypeError::FixedArraySize(sz) = terr else {
1800+
let TypeError::ArraySize(sz) = terr else {
18011801
return None;
18021802
};
18031803
let tykind = match self.tcx.hir_node_by_def_id(trace.cause.body_id) {
@@ -1838,9 +1838,14 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
18381838
if let Some(tykind) = tykind
18391839
&& let hir::TyKind::Array(_, length) = tykind
18401840
&& let hir::ArrayLen::Body(ct) = length
1841+
&& let Some((scalar, ty)) = sz.found.try_to_scalar()
1842+
&& ty == self.tcx.types.usize
18411843
{
18421844
let span = ct.span();
1843-
Some(TypeErrorAdditionalDiags::ConsiderSpecifyingLength { span, length: sz.found })
1845+
Some(TypeErrorAdditionalDiags::ConsiderSpecifyingLength {
1846+
span,
1847+
length: scalar.to_target_usize(&self.tcx).unwrap(),
1848+
})
18441849
} else {
18451850
None
18461851
}

compiler/rustc_type_ir/src/error.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ pub enum TypeError<I: Interner> {
2929
Mutability,
3030
ArgumentMutability(usize),
3131
TupleSize(ExpectedFound<usize>),
32-
FixedArraySize(ExpectedFound<u64>),
32+
ArraySize(ExpectedFound<I::Const>),
3333
ArgCount,
3434

3535
RegionsDoesNotOutlive(I::Region, I::Region),
@@ -69,7 +69,7 @@ impl<I: Interner> TypeError<I> {
6969
use self::TypeError::*;
7070
match self {
7171
CyclicTy(_) | CyclicConst(_) | SafetyMismatch(_) | PolarityMismatch(_) | Mismatch
72-
| AbiMismatch(_) | FixedArraySize(_) | ArgumentSorts(..) | Sorts(_)
72+
| AbiMismatch(_) | ArraySize(_) | ArgumentSorts(..) | Sorts(_)
7373
| VariadicMismatch(_) | TargetFeatureCast(_) => false,
7474

7575
Mutability

compiler/rustc_type_ir/src/inherent.rs

-2
Original file line numberDiff line numberDiff line change
@@ -257,8 +257,6 @@ pub trait Const<I: Interner<Const = Self>>:
257257
+ Relate<I>
258258
+ Flags
259259
{
260-
fn try_to_target_usize(self, interner: I) -> Option<u64>;
261-
262260
fn new_infer(interner: I, var: ty::InferConst) -> Self;
263261

264262
fn new_var(interner: I, var: ty::ConstVid) -> Self;

compiler/rustc_type_ir/src/relate.rs

+3-12
Original file line numberDiff line numberDiff line change
@@ -501,19 +501,10 @@ pub fn structurally_relate_tys<I: Interner, R: TypeRelation<I>>(
501501
let t = relation.relate(a_t, b_t)?;
502502
match relation.relate(sz_a, sz_b) {
503503
Ok(sz) => Ok(Ty::new_array_with_const_len(cx, t, sz)),
504-
Err(err) => {
505-
// Check whether the lengths are both concrete/known values,
506-
// but are unequal, for better diagnostics.
507-
let sz_a = sz_a.try_to_target_usize(cx);
508-
let sz_b = sz_b.try_to_target_usize(cx);
509-
510-
match (sz_a, sz_b) {
511-
(Some(sz_a_val), Some(sz_b_val)) if sz_a_val != sz_b_val => {
512-
Err(TypeError::FixedArraySize(ExpectedFound::new(sz_a_val, sz_b_val)))
513-
}
514-
_ => Err(err),
515-
}
504+
Err(TypeError::ConstMismatch(_)) => {
505+
Err(TypeError::ArraySize(ExpectedFound::new(sz_a, sz_b)))
516506
}
507+
Err(e) => Err(e),
517508
}
518509
}
519510

src/bootstrap/src/core/build_steps/test.rs

+66-1
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,14 @@
33
//! `./x.py test` (aka [`Kind::Test`]) is currently allowed to reach build steps in other modules.
44
//! However, this contains ~all test parts we expect people to be able to build and run locally.
55
6+
use std::collections::HashSet;
67
use std::ffi::{OsStr, OsString};
78
use std::path::{Path, PathBuf};
89
use std::{env, fs, iter};
910

1011
use clap_complete::shells;
1112

13+
use crate::core::build_steps::compile::run_cargo;
1214
use crate::core::build_steps::doc::DocumentationFormat;
1315
use crate::core::build_steps::synthetic_targets::MirOptPanicAbortSyntheticTarget;
1416
use crate::core::build_steps::tool::{self, SourceType, Tool};
@@ -2185,6 +2187,7 @@ struct BookTest {
21852187
path: PathBuf,
21862188
name: &'static str,
21872189
is_ext_doc: bool,
2190+
dependencies: Vec<&'static str>,
21882191
}
21892192

21902193
impl Step for BookTest {
@@ -2237,6 +2240,57 @@ impl BookTest {
22372240
// Books often have feature-gated example text.
22382241
rustbook_cmd.env("RUSTC_BOOTSTRAP", "1");
22392242
rustbook_cmd.env("PATH", new_path).arg("test").arg(path);
2243+
2244+
// Books may also need to build dependencies. For example, `TheBook` has
2245+
// code samples which use the `trpl` crate. For the `rustdoc` invocation
2246+
// to find them them successfully, they need to be built first and their
2247+
// paths used to generate the
2248+
let libs = if !self.dependencies.is_empty() {
2249+
let mut lib_paths = vec![];
2250+
for dep in self.dependencies {
2251+
let mode = Mode::ToolRustc;
2252+
let target = builder.config.build;
2253+
let cargo = tool::prepare_tool_cargo(
2254+
builder,
2255+
compiler,
2256+
mode,
2257+
target,
2258+
Kind::Build,
2259+
dep,
2260+
SourceType::Submodule,
2261+
&[],
2262+
);
2263+
2264+
let stamp = builder
2265+
.cargo_out(compiler, mode, target)
2266+
.join(PathBuf::from(dep).file_name().unwrap())
2267+
.with_extension("stamp");
2268+
2269+
let output_paths = run_cargo(builder, cargo, vec![], &stamp, vec![], false, false);
2270+
let directories = output_paths
2271+
.into_iter()
2272+
.filter_map(|p| p.parent().map(ToOwned::to_owned))
2273+
.fold(HashSet::new(), |mut set, dir| {
2274+
set.insert(dir);
2275+
set
2276+
});
2277+
2278+
lib_paths.extend(directories);
2279+
}
2280+
lib_paths
2281+
} else {
2282+
vec![]
2283+
};
2284+
2285+
if !libs.is_empty() {
2286+
let paths = libs
2287+
.into_iter()
2288+
.map(|path| path.into_os_string())
2289+
.collect::<Vec<OsString>>()
2290+
.join(OsStr::new(","));
2291+
rustbook_cmd.args([OsString::from("--library-path"), paths]);
2292+
}
2293+
22402294
builder.add_rust_test_threads(&mut rustbook_cmd);
22412295
let _guard = builder.msg(
22422296
Kind::Test,
@@ -2295,6 +2349,7 @@ macro_rules! test_book {
22952349
$name:ident, $path:expr, $book_name:expr,
22962350
default=$default:expr
22972351
$(,submodules = $submodules:expr)?
2352+
$(,dependencies=$dependencies:expr)?
22982353
;
22992354
)+) => {
23002355
$(
@@ -2324,11 +2379,21 @@ macro_rules! test_book {
23242379
builder.require_submodule(submodule, None);
23252380
}
23262381
)*
2382+
2383+
let dependencies = vec![];
2384+
$(
2385+
let mut dependencies = dependencies;
2386+
for dep in $dependencies {
2387+
dependencies.push(dep);
2388+
}
2389+
)?
2390+
23272391
builder.ensure(BookTest {
23282392
compiler: self.compiler,
23292393
path: PathBuf::from($path),
23302394
name: $book_name,
23312395
is_ext_doc: !$default,
2396+
dependencies,
23322397
});
23332398
}
23342399
}
@@ -2343,7 +2408,7 @@ test_book!(
23432408
RustcBook, "src/doc/rustc", "rustc", default=true;
23442409
RustByExample, "src/doc/rust-by-example", "rust-by-example", default=false, submodules=["src/doc/rust-by-example"];
23452410
EmbeddedBook, "src/doc/embedded-book", "embedded-book", default=false, submodules=["src/doc/embedded-book"];
2346-
TheBook, "src/doc/book", "book", default=false, submodules=["src/doc/book"];
2411+
TheBook, "src/doc/book", "book", default=false, submodules=["src/doc/book"], dependencies=["src/doc/book/packages/trpl"];
23472412
UnstableBook, "src/doc/unstable-book", "unstable-book", default=true;
23482413
EditionGuide, "src/doc/edition-guide", "edition-guide", default=false, submodules=["src/doc/edition-guide"];
23492414
);

src/bootstrap/src/core/build_steps/vendor.rs

+1
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ pub fn default_paths_to_vendor(builder: &Builder<'_>) -> Vec<(PathBuf, Vec<&'sta
2020
("src/tools/rustbook/Cargo.toml", SUBMODULES_FOR_RUSTBOOK.into()),
2121
("src/tools/rustc-perf/Cargo.toml", vec!["src/tools/rustc-perf"]),
2222
("src/tools/opt-dist/Cargo.toml", vec![]),
23+
("src/doc/book/packages/trpl/Cargo.toml", vec![]),
2324
]
2425
.into_iter()
2526
.map(|(path, submodules)| (builder.src.join(path), submodules))

src/doc/book

Submodule book updated 884 files

src/tools/rustbook/Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ env_logger = "0.11"
1212
mdbook-trpl-listing = { path = "../../doc/book/packages/mdbook-trpl-listing" }
1313
mdbook-trpl-note = { path = "../../doc/book/packages/mdbook-trpl-note" }
1414
mdbook-i18n-helpers = "0.3.3"
15-
mdbook-spec = { path = "../../doc/reference/mdbook-spec"}
15+
mdbook-spec = { path = "../../doc/reference/mdbook-spec" }
1616

1717
[dependencies.mdbook]
1818
version = "0.4.37"

src/tools/rustbook/src/main.rs

+27-4
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,20 @@ fn main() {
3131
(Defaults to the current directory when omitted)")
3232
.value_parser(clap::value_parser!(PathBuf));
3333

34+
// Note: we don't parse this into a `PathBuf` because it is comma separated
35+
// strings *and* we will ultimately pass it into `MDBook::test()`, which
36+
// accepts `Vec<&str>`. Although it is a bit annoying that `-l/--lang` and
37+
// `-L/--library-path` are so close, this is the same set of arguments we
38+
// would pass when invoking mdbook on the CLI, so making them match when
39+
// invoking rustbook makes for good consistency.
40+
let library_path_arg = arg!(
41+
-L --"library-path" <PATHS>
42+
"A comma-separated list of directories to add to the crate search\n\
43+
path when building tests"
44+
)
45+
.required(false)
46+
.value_parser(parse_library_paths);
47+
3448
let matches = Command::new("rustbook")
3549
.about("Build a book with mdBook")
3650
.author("Steve Klabnik <steve@steveklabnik.com>")
@@ -48,11 +62,12 @@ fn main() {
4862
.subcommand(
4963
Command::new("test")
5064
.about("Tests that a book's Rust code samples compile")
51-
.arg(dir_arg),
65+
.arg(dir_arg)
66+
.arg(library_path_arg),
5267
)
5368
.get_matches();
5469

55-
// Check which subcomamnd the user ran...
70+
// Check which subcommand the user ran...
5671
match matches.subcommand() {
5772
Some(("build", sub_matches)) => {
5873
if let Err(e) = build(sub_matches) {
@@ -113,8 +128,12 @@ pub fn build(args: &ArgMatches) -> Result3<()> {
113128

114129
fn test(args: &ArgMatches) -> Result3<()> {
115130
let book_dir = get_book_dir(args);
131+
let library_paths = args
132+
.try_get_one::<Vec<String>>("library-path")?
133+
.map(|v| v.iter().map(|s| s.as_str()).collect::<Vec<&str>>())
134+
.unwrap_or_default();
116135
let mut book = load_book(&book_dir)?;
117-
book.test(vec![])
136+
book.test(library_paths)
118137
}
119138

120139
fn get_book_dir(args: &ArgMatches) -> PathBuf {
@@ -132,12 +151,16 @@ fn load_book(book_dir: &Path) -> Result3<MDBook> {
132151
Ok(book)
133152
}
134153

154+
fn parse_library_paths(input: &str) -> Result<Vec<String>, String> {
155+
Ok(input.split(",").map(String::from).collect())
156+
}
157+
135158
fn handle_error(error: mdbook::errors::Error) -> ! {
136159
eprintln!("Error: {}", error);
137160

138161
for cause in error.chain().skip(1) {
139162
eprintln!("\tCaused By: {}", cause);
140163
}
141164

142-
::std::process::exit(101);
165+
std::process::exit(101);
143166
}

tests/crashes/126359.rs

-9
This file was deleted.

tests/crashes/131101.rs

-12
This file was deleted.

tests/ui/array-slice-vec/match_arr_unknown_len.stderr

+1-4
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,7 @@ error[E0308]: mismatched types
22
--> $DIR/match_arr_unknown_len.rs:3:9
33
|
44
LL | [1, 2] => true,
5-
| ^^^^^^ expected `2`, found `N`
6-
|
7-
= note: expected array `[u32; 2]`
8-
found array `[u32; N]`
5+
| ^^^^^^ expected an array with a size of 2, found one with a size of N
96

107
error: aborting due to 1 previous error
118

0 commit comments

Comments
 (0)