Skip to content

Commit e37f859

Browse files
committed
Auto merge of #33556 - steveklabnik:rollup, r=steveklabnik
Rollup of 9 pull requests - Successful merges: #33129, #33260, #33345, #33386, #33522, #33524, #33528, #33539, #33542 - Failed merges: #33342, #33475, #33517
2 parents c049541 + 403970f commit e37f859

File tree

13 files changed

+262
-20
lines changed

13 files changed

+262
-20
lines changed

src/doc/nomicon/vec-alloc.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ LLVM needs to work with different languages' semantics and custom allocators,
150150
it can't really intimately understand allocation. Instead, the main idea behind
151151
allocation is "doesn't overlap with other stuff". That is, heap allocations,
152152
stack allocations, and globals don't randomly overlap. Yep, it's about alias
153-
analysis. As such, Rust can technically play a bit fast an loose with the notion of
153+
analysis. As such, Rust can technically play a bit fast and loose with the notion of
154154
an allocation as long as it's *consistent*.
155155

156156
Getting back to the empty allocation case, there are a couple of places where

src/liballoc/raw_vec.rs

+1
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,7 @@ impl<T> RawVec<T> {
147147
/// Gets the capacity of the allocation.
148148
///
149149
/// This will always be `usize::MAX` if `T` is zero-sized.
150+
#[inline(always)]
150151
pub fn cap(&self) -> usize {
151152
if mem::size_of::<T>() == 0 {
152153
!0

src/libcollections/fmt.rs

+12
Original file line numberDiff line numberDiff line change
@@ -521,12 +521,24 @@ use string;
521521
///
522522
/// # Examples
523523
///
524+
/// Basic usage:
525+
///
524526
/// ```
525527
/// use std::fmt;
526528
///
527529
/// let s = fmt::format(format_args!("Hello, {}!", "world"));
528530
/// assert_eq!(s, "Hello, world!".to_string());
529531
/// ```
532+
///
533+
/// Please note that using [`format!`][format!] might be preferrable.
534+
/// Example:
535+
///
536+
/// ```
537+
/// let s = format!("Hello, {}!", "world");
538+
/// assert_eq!(s, "Hello, world!".to_string());
539+
/// ```
540+
///
541+
/// [format!]: ../macro.format!.html
530542
#[stable(feature = "rust1", since = "1.0.0")]
531543
pub fn format(args: Arguments) -> string::String {
532544
let mut output = string::String::new();

src/libcore/fmt/mod.rs

+26
Original file line numberDiff line numberDiff line change
@@ -776,6 +776,32 @@ pub trait UpperExp {
776776
///
777777
/// * output - the buffer to write output to
778778
/// * args - the precompiled arguments generated by `format_args!`
779+
///
780+
/// # Examples
781+
///
782+
/// Basic usage:
783+
///
784+
/// ```
785+
/// use std::fmt;
786+
///
787+
/// let mut output = String::new();
788+
/// fmt::write(&mut output, format_args!("Hello {}!", "world"))
789+
/// .expect("Error occurred while trying to write in String");
790+
/// assert_eq!(output, "Hello world!");
791+
/// ```
792+
///
793+
/// Please note that using [`write!`][write_macro] might be preferrable. Example:
794+
///
795+
/// ```
796+
/// use std::fmt::Write;
797+
///
798+
/// let mut output = String::new();
799+
/// write!(&mut output, "Hello {}!", "world")
800+
/// .expect("Error occurred while trying to write in String");
801+
/// assert_eq!(output, "Hello world!");
802+
/// ```
803+
///
804+
/// [write_macro]: ../../std/macro.write!.html
779805
#[stable(feature = "rust1", since = "1.0.0")]
780806
pub fn write(output: &mut Write, args: Arguments) -> Result {
781807
let mut formatter = Formatter {

src/librustc/infer/region_inference/mod.rs

-3
Original file line numberDiff line numberDiff line change
@@ -1240,9 +1240,6 @@ impl<'a, 'gcx, 'tcx> RegionVarBindings<'a, 'gcx, 'tcx> {
12401240
orig_node_idx,
12411241
node_idx);
12421242

1243-
// figure out the direction from which this node takes its
1244-
// values, and search for concrete regions etc in that direction
1245-
let dir = graph::INCOMING;
12461243
process_edges(self, &mut state, graph, node_idx, dir);
12471244
}
12481245

src/librustc/middle/resolve_lifetime.rs

+6-1
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,12 @@ impl<'a, 'v> Visitor<'v> for LifetimeContext<'a> {
193193
})
194194
}
195195
FnKind::Closure(_) => {
196-
self.add_scope_and_walk_fn(fk, fd, b, s, fn_id)
196+
// Closures have their own set of labels, save labels just
197+
// like for foreign items above.
198+
let saved = replace(&mut self.labels_in_fn, vec![]);
199+
let result = self.add_scope_and_walk_fn(fk, fd, b, s, fn_id);
200+
replace(&mut self.labels_in_fn, saved);
201+
result
197202
}
198203
}
199204
}

src/librustc_borrowck/diagnostics.rs

+104-1
Original file line numberDiff line numberDiff line change
@@ -454,6 +454,110 @@ fn foo(a: &mut i32) {
454454
```
455455
"##,
456456

457+
E0504: r##"
458+
This error occurs when an attempt is made to move a borrowed variable into a
459+
closure.
460+
461+
Example of erroneous code:
462+
463+
```compile_fail
464+
struct FancyNum {
465+
num: u8
466+
}
467+
468+
fn main() {
469+
let fancy_num = FancyNum { num: 5 };
470+
let fancy_ref = &fancy_num;
471+
472+
let x = move || {
473+
println!("child function: {}", fancy_num.num);
474+
// error: cannot move `fancy_num` into closure because it is borrowed
475+
};
476+
477+
x();
478+
println!("main function: {}", fancy_ref.num);
479+
}
480+
```
481+
482+
Here, `fancy_num` is borrowed by `fancy_ref` and so cannot be moved into
483+
the closure `x`. There is no way to move a value into a closure while it is
484+
borrowed, as that would invalidate the borrow.
485+
486+
If the closure can't outlive the value being moved, try using a reference
487+
rather than moving:
488+
489+
```
490+
struct FancyNum {
491+
num: u8
492+
}
493+
494+
fn main() {
495+
let fancy_num = FancyNum { num: 5 };
496+
let fancy_ref = &fancy_num;
497+
498+
let x = move || {
499+
// fancy_ref is usable here because it doesn't move `fancy_num`
500+
println!("child function: {}", fancy_ref.num);
501+
};
502+
503+
x();
504+
505+
println!("main function: {}", fancy_num.num);
506+
}
507+
```
508+
509+
If the value has to be borrowed and then moved, try limiting the lifetime of
510+
the borrow using a scoped block:
511+
512+
```
513+
struct FancyNum {
514+
num: u8
515+
}
516+
517+
fn main() {
518+
let fancy_num = FancyNum { num: 5 };
519+
520+
{
521+
let fancy_ref = &fancy_num;
522+
println!("main function: {}", fancy_ref.num);
523+
// `fancy_ref` goes out of scope here
524+
}
525+
526+
let x = move || {
527+
// `fancy_num` can be moved now (no more references exist)
528+
println!("child function: {}", fancy_num.num);
529+
};
530+
531+
x();
532+
}
533+
```
534+
535+
If the lifetime of a reference isn't enough, such as in the case of threading,
536+
consider using an `Arc` to create a reference-counted value:
537+
538+
```
539+
use std::sync::Arc;
540+
use std::thread;
541+
542+
struct FancyNum {
543+
num: u8
544+
}
545+
546+
fn main() {
547+
let fancy_ref1 = Arc::new(FancyNum { num: 5 });
548+
let fancy_ref2 = fancy_ref1.clone();
549+
550+
let x = thread::spawn(move || {
551+
// `fancy_ref1` can be moved and has a `'static` lifetime
552+
println!("child thread: {}", fancy_ref1.num);
553+
});
554+
555+
x.join().expect("child thread should finish");
556+
println!("main thread: {}", fancy_ref2.num);
557+
}
558+
```
559+
"##,
560+
457561
E0506: r##"
458562
This error occurs when an attempt is made to assign to a borrowed value.
459563
@@ -756,7 +860,6 @@ register_diagnostics! {
756860
E0500, // closure requires unique access to `..` but .. is already borrowed
757861
E0502, // cannot borrow `..`.. as .. because .. is also borrowed as ...
758862
E0503, // cannot use `..` because it was mutably borrowed
759-
E0504, // cannot move `..` into closure because it is borrowed
760863
E0505, // cannot move out of `..` because it is borrowed
761864
E0508, // cannot move out of type `..`, a non-copy fixed-size array
762865
E0524, // two closures require unique access to `..` at the same time

src/librustc_const_eval/diagnostics.rs

+51-10
Original file line numberDiff line numberDiff line change
@@ -215,22 +215,63 @@ match Some("hi".to_string()) {
215215
The variable `s` has type `String`, and its use in the guard is as a variable of
216216
type `String`. The guard code effectively executes in a separate scope to the
217217
body of the arm, so the value would be moved into this anonymous scope and
218-
therefore become unavailable in the body of the arm. Although this example seems
219-
innocuous, the problem is most clear when considering functions that take their
220-
argument by value.
218+
therefore becomes unavailable in the body of the arm.
221219
222-
```compile_fail
220+
The problem above can be solved by using the `ref` keyword.
221+
222+
```
223223
match Some("hi".to_string()) {
224-
Some(s) if { drop(s); false } => (),
225-
Some(s) => {}, // use s.
224+
Some(ref s) if s.len() == 0 => {},
226225
_ => {},
227226
}
228227
```
229228
230-
The value would be dropped in the guard then become unavailable not only in the
231-
body of that arm but also in all subsequent arms! The solution is to bind by
232-
reference when using guards or refactor the entire expression, perhaps by
233-
putting the condition inside the body of the arm.
229+
Though this example seems innocuous and easy to solve, the problem becomes clear
230+
when it encounters functions which consume the value:
231+
232+
```compile_fail
233+
struct A{}
234+
235+
impl A {
236+
fn consume(self) -> usize {
237+
0
238+
}
239+
}
240+
241+
fn main() {
242+
let a = Some(A{});
243+
match a {
244+
Some(y) if y.consume() > 0 => {}
245+
_ => {}
246+
}
247+
}
248+
```
249+
250+
In this situation, even the `ref` keyword cannot solve it, since borrowed
251+
content cannot be moved. This problem cannot be solved generally. If the value
252+
can be cloned, here is a not-so-specific solution:
253+
254+
```
255+
#[derive(Clone)]
256+
struct A{}
257+
258+
impl A {
259+
fn consume(self) -> usize {
260+
0
261+
}
262+
}
263+
264+
fn main() {
265+
let a = Some(A{});
266+
match a{
267+
Some(ref y) if y.clone().consume() > 0 => {}
268+
_ => {}
269+
}
270+
}
271+
```
272+
273+
If the value will be consumed in the pattern guard, using its clone will not
274+
move its ownership, so the code works.
234275
"##,
235276

236277
E0009: r##"

src/librustc_typeck/diagnostics.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -742,7 +742,7 @@ fn f(a: u16, b: &str) {}
742742
743743
Must always be called with exactly two arguments, e.g. `f(2, "test")`.
744744
745-
Note, that Rust does not have a notion of optional function arguments or
745+
Note that Rust does not have a notion of optional function arguments or
746746
variadic functions (except for its C-FFI).
747747
"##,
748748

src/librustdoc/html/render.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -1537,7 +1537,6 @@ impl<'a> Item<'a> {
15371537
}
15381538
}
15391539

1540-
15411540
impl<'a> fmt::Display for Item<'a> {
15421541
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
15431542
debug_assert!(!self.item.is_stripped());
@@ -1575,6 +1574,9 @@ impl<'a> fmt::Display for Item<'a> {
15751574

15761575
write!(fmt, "</span>")?; // in-band
15771576
write!(fmt, "<span class='out-of-band'>")?;
1577+
if let Some(version) = self.item.stable_since() {
1578+
write!(fmt, "<span class='since'>{}</span>", version)?;
1579+
}
15781580
write!(fmt,
15791581
r##"<span id='render-detail'>
15801582
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
@@ -1922,7 +1924,6 @@ fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
19221924
generics = f.generics,
19231925
where_clause = WhereClause(&f.generics),
19241926
decl = f.decl)?;
1925-
render_stability_since_raw(w, it.stable_since(), None)?;
19261927
document(w, cx, it)
19271928
}
19281929

@@ -2236,7 +2237,6 @@ fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
22362237
"",
22372238
true)?;
22382239
write!(w, "</pre>")?;
2239-
render_stability_since_raw(w, it.stable_since(), None)?;
22402240

22412241
document(w, cx, it)?;
22422242
let mut fields = s.fields.iter().filter(|f| {

src/librustdoc/html/static/rustdoc.css

+6
Original file line numberDiff line numberDiff line change
@@ -634,6 +634,12 @@ a.test-arrow {
634634
padding-left: 10px;
635635
}
636636

637+
span.since {
638+
position: initial;
639+
font-size: 20px;
640+
margin-right: 5px;
641+
}
642+
637643
/* Media Queries */
638644

639645
@media (max-width: 700px) {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
// This test checks that the error messages you get for this example
12+
// at least mention `'a` and `'static`. The precise messages can drift
13+
// over time, but this test used to exhibit some pretty bogus messages
14+
// that were not remotely helpful.
15+
16+
// error-pattern:cannot infer
17+
// error-pattern:cannot outlive the lifetime 'a
18+
// error-pattern:must be valid for the static lifetime
19+
// error-pattern:cannot infer
20+
// error-pattern:cannot outlive the lifetime 'a
21+
// error-pattern:must be valid for the static lifetime
22+
23+
struct Invariant<'a>(Option<&'a mut &'a mut ()>);
24+
25+
fn mk_static() -> Invariant<'static> { Invariant(None) }
26+
27+
fn unify<'a>(x: Option<Invariant<'a>>, f: fn(Invariant<'a>)) {
28+
let bad = if x.is_some() {
29+
x.unwrap()
30+
} else {
31+
mk_static()
32+
};
33+
f(bad);
34+
}
35+
36+
fn main() {}

0 commit comments

Comments
 (0)