Skip to content

Commit cca7ee5

Browse files
committed
Auto merge of rust-lang#112025 - matthiaskrgr:rollup-j693v67, r=matthiaskrgr
Rollup of 6 pull requests Successful merges: - rust-lang#108630 (Fix docs for `alloc::realloc`) - rust-lang#109084 (rustc driver: Remove argument 0 before at-expansion to prevent ICE) - rust-lang#111181 (fix(parse): return unpected when current token is EOF) - rust-lang#111656 (Use an unbounded lifetime in `String::leak`.) - rust-lang#111946 (rustdoc: Add `ItemTemplate` trait and related functions to avoid repetitively wrapping existing functions) - rust-lang#112018 (Clean up usage of `cx.tcx` when `tcx` is already set into a variable) r? `@ghost` `@rustbot` modify labels: rollup
2 parents bc428f8 + 9f5dce7 commit cca7ee5

File tree

19 files changed

+141
-94
lines changed

19 files changed

+141
-94
lines changed

compiler/rustc_driver_impl/src/args.rs

+3
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@ fn arg_expand(arg: String) -> Result<Vec<String>, Error> {
1818
}
1919
}
2020

21+
/// **Note:** This function doesn't interpret argument 0 in any special way.
22+
/// If this function is intended to be used with command line arguments,
23+
/// `argv[0]` must be removed prior to calling it manually.
2124
pub fn arg_expand_all(at_args: &[String]) -> Vec<String> {
2225
let mut args = Vec::new();
2326
for arg in at_args {

compiler/rustc_driver_impl/src/lib.rs

+10-3
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,16 @@ fn run_compiler(
250250
Box<dyn FnOnce(&config::Options) -> Box<dyn CodegenBackend> + Send>,
251251
>,
252252
) -> interface::Result<()> {
253+
// Throw away the first argument, the name of the binary.
254+
// In case of at_args being empty, as might be the case by
255+
// passing empty argument array to execve under some platforms,
256+
// just use an empty slice.
257+
//
258+
// This situation was possible before due to arg_expand_all being
259+
// called before removing the argument, enabling a crash by calling
260+
// the compiler with @empty_file as argv[0] and no more arguments.
261+
let at_args = at_args.get(1..).unwrap_or_default();
262+
253263
let args = args::arg_expand_all(at_args);
254264

255265
let Some(matches) = handle_options(&args) else { return Ok(()) };
@@ -1074,9 +1084,6 @@ fn print_flag_list<T>(
10741084
/// So with all that in mind, the comments below have some more detail about the
10751085
/// contortions done here to get things to work out correctly.
10761086
pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
1077-
// Throw away the first argument, the name of the binary
1078-
let args = &args[1..];
1079-
10801087
if args.is_empty() {
10811088
// user did not write `-v` nor `-Z unstable-options`, so do not
10821089
// include that extra information.

compiler/rustc_parse/src/parser/mod.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -536,7 +536,9 @@ impl<'a> Parser<'a> {
536536
} else if inedible.contains(&self.token.kind) {
537537
// leave it in the input
538538
Ok(false)
539-
} else if self.last_unexpected_token_span == Some(self.token.span) {
539+
} else if self.token.kind != token::Eof
540+
&& self.last_unexpected_token_span == Some(self.token.span)
541+
{
540542
FatalError.raise();
541543
} else {
542544
self.expected_one_of_not_found(edible, inedible)

library/alloc/src/string.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1851,7 +1851,7 @@ impl String {
18511851
}
18521852

18531853
/// Consumes and leaks the `String`, returning a mutable reference to the contents,
1854-
/// `&'static mut str`.
1854+
/// `&'a mut str`.
18551855
///
18561856
/// This is mainly useful for data that lives for the remainder of
18571857
/// the program's life. Dropping the returned reference will cause a memory
@@ -1874,7 +1874,7 @@ impl String {
18741874
/// ```
18751875
#[unstable(feature = "string_leak", issue = "102929")]
18761876
#[inline]
1877-
pub fn leak(self) -> &'static mut str {
1877+
pub fn leak<'a>(self) -> &'a mut str {
18781878
let slice = self.vec.leak();
18791879
unsafe { from_utf8_unchecked_mut(slice) }
18801880
}

library/core/src/alloc/global.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,8 @@ pub unsafe trait GlobalAlloc {
235235
/// * `new_size` must be greater than zero.
236236
///
237237
/// * `new_size`, when rounded up to the nearest multiple of `layout.align()`,
238-
/// must not overflow (i.e., the rounded value must be less than `usize::MAX`).
238+
/// must not overflow isize (i.e., the rounded value must be less than or
239+
/// equal to `isize::MAX`).
239240
///
240241
/// (Extension subtraits might provide more specific bounds on
241242
/// behavior, e.g., guarantee a sentinel address or a null pointer

src/librustdoc/clean/inline.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -355,9 +355,9 @@ pub(crate) fn build_impl(
355355
return;
356356
}
357357

358-
let _prof_timer = cx.tcx.sess.prof.generic_activity("build_impl");
359-
360358
let tcx = cx.tcx;
359+
let _prof_timer = tcx.sess.prof.generic_activity("build_impl");
360+
361361
let associated_trait = tcx.impl_trait_ref(did).map(ty::EarlyBinder::skip_binder);
362362

363363
// Only inline impl if the implemented trait is

src/librustdoc/clean/utils.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@ pub(crate) fn build_deref_target_impls(
193193
};
194194

195195
if let Some(prim) = target.primitive_type() {
196-
let _prof_timer = cx.tcx.sess.prof.generic_activity("build_primitive_inherent_impls");
196+
let _prof_timer = tcx.sess.prof.generic_activity("build_primitive_inherent_impls");
197197
for did in prim.impls(tcx).filter(|did| !did.is_local()) {
198198
inline::build_impl(cx, did, None, ret);
199199
}

src/librustdoc/config.rs

-1
Original file line numberDiff line numberDiff line change
@@ -314,7 +314,6 @@ impl Options {
314314
matches: &getopts::Matches,
315315
args: Vec<String>,
316316
) -> Result<(Options, RenderOptions), i32> {
317-
let args = &args[1..];
318317
// Check for unstable options.
319318
nightly_options::check_nightly_options(matches, &opts());
320319

src/librustdoc/formats/cache.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ impl Cache {
147147

148148
// Cache where all our extern crates are located
149149
// FIXME: this part is specific to HTML so it'd be nice to remove it from the common code
150-
for &crate_num in cx.tcx.crates(()) {
150+
for &crate_num in tcx.crates(()) {
151151
let e = ExternalCrate { crate_num };
152152

153153
let name = e.name(tcx);

src/librustdoc/html/render/print_item.rs

+65-47
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ use rustc_middle::middle::stability;
99
use rustc_middle::ty::{self, TyCtxt};
1010
use rustc_span::hygiene::MacroKind;
1111
use rustc_span::symbol::{kw, sym, Symbol};
12+
use std::borrow::Borrow;
13+
use std::cell::{RefCell, RefMut};
1214
use std::cmp::Ordering;
1315
use std::fmt;
1416
use std::rc::Rc;
@@ -216,6 +218,53 @@ fn toggle_close(mut w: impl fmt::Write) {
216218
w.write_str("</details>").unwrap();
217219
}
218220

221+
trait ItemTemplate<'a, 'cx: 'a>: askama::Template + fmt::Display {
222+
fn item_and_mut_cx(&self) -> (&'a clean::Item, RefMut<'_, &'a mut Context<'cx>>);
223+
}
224+
225+
fn item_template_document<'a: 'b, 'b, 'cx: 'a>(
226+
templ: &'b impl ItemTemplate<'a, 'cx>,
227+
) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
228+
display_fn(move |f| {
229+
let (item, mut cx) = templ.item_and_mut_cx();
230+
let v = document(*cx, item, None, HeadingOffset::H2);
231+
write!(f, "{v}")
232+
})
233+
}
234+
235+
fn item_template_document_type_layout<'a: 'b, 'b, 'cx: 'a>(
236+
templ: &'b impl ItemTemplate<'a, 'cx>,
237+
) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
238+
display_fn(move |f| {
239+
let (item, cx) = templ.item_and_mut_cx();
240+
let def_id = item.item_id.expect_def_id();
241+
let v = document_type_layout(*cx, def_id);
242+
write!(f, "{v}")
243+
})
244+
}
245+
246+
fn item_template_render_attributes_in_pre<'a: 'b, 'b, 'cx: 'a>(
247+
templ: &'b impl ItemTemplate<'a, 'cx>,
248+
) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
249+
display_fn(move |f| {
250+
let (item, cx) = templ.item_and_mut_cx();
251+
let tcx = cx.tcx();
252+
let v = render_attributes_in_pre(item, "", tcx);
253+
write!(f, "{v}")
254+
})
255+
}
256+
257+
fn item_template_render_assoc_items<'a: 'b, 'b, 'cx: 'a>(
258+
templ: &'b impl ItemTemplate<'a, 'cx>,
259+
) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
260+
display_fn(move |f| {
261+
let (item, mut cx) = templ.item_and_mut_cx();
262+
let def_id = item.item_id.expect_def_id();
263+
let v = render_assoc_items(*cx, item, def_id, AssocItemRender::All);
264+
write!(f, "{v}")
265+
})
266+
}
267+
219268
fn item_module(w: &mut Buffer, cx: &mut Context<'_>, item: &clean::Item, items: &[clean::Item]) {
220269
write!(w, "{}", document(cx, item, None, HeadingOffset::H2));
221270

@@ -356,18 +405,18 @@ fn item_module(w: &mut Buffer, cx: &mut Context<'_>, item: &clean::Item, items:
356405

357406
clean::ImportItem(ref import) => {
358407
let stab_tags = if let Some(import_def_id) = import.source.did {
359-
let ast_attrs = cx.tcx().get_attrs_unchecked(import_def_id);
408+
let ast_attrs = tcx.get_attrs_unchecked(import_def_id);
360409
let import_attrs = Box::new(clean::Attributes::from_ast(ast_attrs));
361410

362411
// Just need an item with the correct def_id and attrs
363412
let import_item = clean::Item {
364413
item_id: import_def_id.into(),
365414
attrs: import_attrs,
366-
cfg: ast_attrs.cfg(cx.tcx(), &cx.cache().hidden_cfg),
415+
cfg: ast_attrs.cfg(tcx, &cx.cache().hidden_cfg),
367416
..myitem.clone()
368417
};
369418

370-
let stab_tags = Some(extra_info_tags(&import_item, item, cx.tcx()).to_string());
419+
let stab_tags = Some(extra_info_tags(&import_item, item, tcx).to_string());
371420
stab_tags
372421
} else {
373422
None
@@ -405,8 +454,7 @@ fn item_module(w: &mut Buffer, cx: &mut Context<'_>, item: &clean::Item, items:
405454

406455
let unsafety_flag = match *myitem.kind {
407456
clean::FunctionItem(_) | clean::ForeignFunctionItem(_)
408-
if myitem.fn_header(cx.tcx()).unwrap().unsafety
409-
== hir::Unsafety::Unsafe =>
457+
if myitem.fn_header(tcx).unwrap().unsafety == hir::Unsafety::Unsafe =>
410458
{
411459
"<sup title=\"unsafe function\">⚠</sup>"
412460
}
@@ -439,7 +487,7 @@ fn item_module(w: &mut Buffer, cx: &mut Context<'_>, item: &clean::Item, items:
439487
{docs_before}{docs}{docs_after}",
440488
name = myitem.name.unwrap(),
441489
visibility_emoji = visibility_emoji,
442-
stab_tags = extra_info_tags(myitem, item, cx.tcx()),
490+
stab_tags = extra_info_tags(myitem, item, tcx),
443491
class = myitem.type_(),
444492
unsafety_flag = unsafety_flag,
445493
href = item_path(myitem.type_(), myitem.name.unwrap().as_str()),
@@ -886,7 +934,7 @@ fn item_trait(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean:
886934
write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
887935

888936
for implementor in foreign {
889-
let provided_methods = implementor.inner_impl().provided_trait_methods(cx.tcx());
937+
let provided_methods = implementor.inner_impl().provided_trait_methods(tcx);
890938
let assoc_link =
891939
AssocItemLink::GotoSource(implementor.impl_item.item_id, &provided_methods);
892940
render_impl(
@@ -919,7 +967,7 @@ fn item_trait(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean:
919967
}
920968
w.write_str("</div>");
921969

922-
if t.is_auto(cx.tcx()) {
970+
if t.is_auto(tcx) {
923971
write_small_section_header(
924972
w,
925973
"synthetic-implementors",
@@ -948,7 +996,7 @@ fn item_trait(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean:
948996
"<div id=\"implementors-list\"></div>",
949997
);
950998

951-
if t.is_auto(cx.tcx()) {
999+
if t.is_auto(tcx) {
9521000
write_small_section_header(
9531001
w,
9541002
"synthetic-implementors",
@@ -1131,55 +1179,25 @@ fn item_union(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, s: &clean:
11311179
#[derive(Template)]
11321180
#[template(path = "item_union.html")]
11331181
struct ItemUnion<'a, 'cx> {
1134-
cx: std::cell::RefCell<&'a mut Context<'cx>>,
1182+
cx: RefCell<&'a mut Context<'cx>>,
11351183
it: &'a clean::Item,
11361184
s: &'a clean::Union,
11371185
}
11381186

1139-
impl<'a, 'cx: 'a> ItemUnion<'a, 'cx> {
1140-
fn render_assoc_items<'b>(
1141-
&'b self,
1142-
) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
1143-
display_fn(move |f| {
1144-
let def_id = self.it.item_id.expect_def_id();
1145-
let mut cx = self.cx.borrow_mut();
1146-
let v = render_assoc_items(*cx, self.it, def_id, AssocItemRender::All);
1147-
write!(f, "{v}")
1148-
})
1149-
}
1150-
fn document_type_layout<'b>(
1151-
&'b self,
1152-
) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
1153-
display_fn(move |f| {
1154-
let def_id = self.it.item_id.expect_def_id();
1155-
let cx = self.cx.borrow_mut();
1156-
let v = document_type_layout(*cx, def_id);
1157-
write!(f, "{v}")
1158-
})
1187+
impl<'a, 'cx: 'a> ItemTemplate<'a, 'cx> for ItemUnion<'a, 'cx> {
1188+
fn item_and_mut_cx(&self) -> (&'a clean::Item, RefMut<'_, &'a mut Context<'cx>>) {
1189+
(self.it, self.cx.borrow_mut())
11591190
}
1191+
}
1192+
1193+
impl<'a, 'cx: 'a> ItemUnion<'a, 'cx> {
11601194
fn render_union<'b>(&'b self) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
11611195
display_fn(move |f| {
11621196
let cx = self.cx.borrow_mut();
11631197
let v = render_union(self.it, Some(&self.s.generics), &self.s.fields, *cx);
11641198
write!(f, "{v}")
11651199
})
11661200
}
1167-
fn render_attributes_in_pre<'b>(
1168-
&'b self,
1169-
) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
1170-
display_fn(move |f| {
1171-
let tcx = self.cx.borrow().tcx();
1172-
let v = render_attributes_in_pre(self.it, "", tcx);
1173-
write!(f, "{v}")
1174-
})
1175-
}
1176-
fn document<'b>(&'b self) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
1177-
display_fn(move |f| {
1178-
let mut cx = self.cx.borrow_mut();
1179-
let v = document(*cx, self.it, None, HeadingOffset::H2);
1180-
write!(f, "{v}")
1181-
})
1182-
}
11831201
fn document_field<'b>(
11841202
&'b self,
11851203
field: &'a clean::Item,
@@ -1219,7 +1237,7 @@ fn item_union(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, s: &clean:
12191237
}
12201238
}
12211239

1222-
ItemUnion { cx: std::cell::RefCell::new(cx), it, s }.render_into(w).unwrap();
1240+
ItemUnion { cx: RefCell::new(cx), it, s }.render_into(w).unwrap();
12231241
}
12241242

12251243
fn print_tuple_struct_fields<'a, 'cx: 'a>(

src/librustdoc/html/render/type_layout.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -54,13 +54,13 @@ pub(crate) fn document_type_layout<'a, 'cx: 'a>(
5454
} else if let Primitive::Int(i, _) = tag.primitive() {
5555
i.size().bytes()
5656
} else {
57-
span_bug!(cx.tcx().def_span(ty_def_id), "tag is neither niche nor int")
57+
span_bug!(tcx.def_span(ty_def_id), "tag is neither niche nor int")
5858
};
5959
variants
6060
.iter_enumerated()
6161
.map(|(variant_idx, variant_layout)| {
6262
let Adt(adt, _) = type_layout.ty.kind() else {
63-
span_bug!(cx.tcx().def_span(ty_def_id), "not an adt")
63+
span_bug!(tcx.def_span(ty_def_id), "not an adt")
6464
};
6565
let name = adt.variant(variant_idx).name;
6666
let is_unsized = variant_layout.abi.is_unsized();

src/librustdoc/html/templates/item_union.html

+4-4
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
<pre class="rust item-decl"><code>
2-
{{ self.render_attributes_in_pre() | safe }}
2+
{{ self::item_template_render_attributes_in_pre(self.borrow()) | safe }}
33
{{ self.render_union() | safe }}
44
</code></pre>
5-
{{ self.document() | safe }}
5+
{{ self::item_template_document(self.borrow()) | safe }}
66
{% if self.fields_iter().peek().is_some() %}
77
<h2 id="fields" class="fields small-section-header">
88
Fields<a href="#fields" class="anchor">§</a>
@@ -19,5 +19,5 @@ <h2 id="fields" class="fields small-section-header">
1919
{{ self.document_field(field) | safe }}
2020
{% endfor %}
2121
{% endif %}
22-
{{ self.render_assoc_items() | safe }}
23-
{{ self.document_type_layout() | safe }}
22+
{{ self::item_template_render_assoc_items(self.borrow()) | safe }}
23+
{{ self::item_template_document_type_layout(self.borrow()) | safe }}

src/librustdoc/lib.rs

+11-1
Original file line numberDiff line numberDiff line change
@@ -712,13 +712,23 @@ fn run_renderer<'tcx, T: formats::FormatRenderer<'tcx>>(
712712
}
713713

714714
fn main_args(at_args: &[String]) -> MainResult {
715+
// Throw away the first argument, the name of the binary.
716+
// In case of at_args being empty, as might be the case by
717+
// passing empty argument array to execve under some platforms,
718+
// just use an empty slice.
719+
//
720+
// This situation was possible before due to arg_expand_all being
721+
// called before removing the argument, enabling a crash by calling
722+
// the compiler with @empty_file as argv[0] and no more arguments.
723+
let at_args = at_args.get(1..).unwrap_or_default();
724+
715725
let args = rustc_driver::args::arg_expand_all(at_args);
716726

717727
let mut options = getopts::Options::new();
718728
for option in opts() {
719729
(option.apply)(&mut options);
720730
}
721-
let matches = match options.parse(&args[1..]) {
731+
let matches = match options.parse(&args) {
722732
Ok(m) => m,
723733
Err(err) => {
724734
early_error(ErrorOutputType::default(), err.to_string());

src/librustdoc/passes/collect_intra_doc_links.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -723,7 +723,7 @@ fn resolve_associated_trait_item<'a>(
723723
.iter()
724724
.flat_map(|&(impl_, trait_)| {
725725
filter_assoc_items_by_name_and_namespace(
726-
cx.tcx,
726+
tcx,
727727
trait_,
728728
Ident::with_dummy_span(item_name),
729729
ns,
@@ -1743,7 +1743,7 @@ fn resolution_failure(
17431743
if let Ok(v_res) = collector.resolve(start, ns, item_id, module_id) {
17441744
debug!("found partial_res={:?}", v_res);
17451745
if !v_res.is_empty() {
1746-
*partial_res = Some(full_res(collector.cx.tcx, v_res[0]));
1746+
*partial_res = Some(full_res(tcx, v_res[0]));
17471747
*unresolved = end.into();
17481748
break 'outer;
17491749
}

0 commit comments

Comments
 (0)